0

I want to run an interactive program where a user is prompted to enter a number of students. If the user inputs a letter or other character besides a whole number, they should be asked again ("Enter the number of students: ")

I have the following code:

public int[] createArrays(Scanner s) {
    int size;
    System.out.print("Enter the number of students: ");
    size = s.nextInt();** 
    int scores[] = new int[size];
    System.out.println("Enter " + size + " scores:");
    for (int i = 0; i < size; i++) {
      scores[i]=getValidInt(s,"Score " + (i + 1) + ": ");
    }
    return scores;
}

How can I create a loop for this?

Lora Croft
  • 3
  • 1
  • 2
  • Does this answer your question? [How to loop user input until an integer is inputted?](https://stackoverflow.com/questions/19130217/how-to-loop-user-input-until-an-integer-is-inputted) – Vinay Hegde May 01 '20 at 05:18
  • @Eva Klein, did you check this post https://stackoverflow.com/questions/25277286/exception-handling-with-scanner-nextint-vs-scanner-nextline – JenilDave May 01 '20 at 05:19

4 Answers4

1

Let's add a loop, take the value as String and check if it is a number:

String sizeString;
int size;
Scanner s = new Scanner(System.in);
do {
        System.out.print("Enter the number of students: ");
        sizeString = s.nextLine();

} while (!(sizeString.matches("[0-9]+") && sizeString.length() > 0));
size = Integer.parseInt(sizeString);
1

Try catching the exception and handling it until you get the desired input.

int numberOfStudents;

while(true)
{
    try {
        System.out.print("Enter the number of student: ");
        numberOfStudents = Integer.parseInt(s.next());
        break;
    }
    catch(NumberFormatException e) {
        System.out.println("You have not entered an Integer!");
    }
}

//Then assign numberOfStudents to the score array
int scores[] = new int[numberOfStudents]
Bradley
  • 327
  • 2
  • 11
0

try this

public int[] createArrays(Scanner s) {
    int size;
    System.out.print("Enter the number of students: ");

    while(true) {
        try {
              size = Integer.parseInt(s.nextLine());
              break;
        }catch (NumberFormatException e) {
            System.out.println();
            System.out.println("You have entered wrong number");
            System.out.print("Enter again the number of students: ");
            continue;
        }
    }

    int scores[] = new int[size];
    System.out.println("Enter " + size + " scores:");
    for (int i = 0; i < size; i++) {
      scores[i]=getValidInt(s,"Score " + (i + 1) + ": ");
    }
    return scores;
}
Sachin Kumar
  • 1,055
  • 9
  • 15
0

int no1 = 0;

Scanner scanner = new Scanner(System.in);

    while(true)
    {
        try {
            System.out.print("Number 1: ");
            no1 = Integer.parseInt(scanner.next());
            break;
        }
        catch(NumberFormatException e) {
            System.out.println("..You have not entered valid value!");
        }
    }