Lora Croft
Lora Croft

Reputation: 3

How to loop a user input until integer is entered?

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?

Upvotes: 0

Views: 5051

Answers (4)

Dulantha Madushan
Dulantha Madushan

Reputation: 1

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!");
        }
    }

Upvotes: 0

Bradley
Bradley

Reputation: 337

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]

Upvotes: 1

Sachin Kumar
Sachin Kumar

Reputation: 1169

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;
}

Upvotes: 0

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);

Upvotes: 1

Related Questions