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?

2

4 Answers 4

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);
Sign up to request clarification or add additional context in comments.

Comments

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]

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.