如何循环用户输入,直到输入整数?

2022-07-23 00:00:00 input loops while-loop for-loop java

我想运行一个交互式程序,提示用户输入一些学生。如果用户除输入整数外还输入字母或其他字符,则应再次询问("输入学生人数:")

我有以下代码:

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

如何为此创建循环?


解决方案

试试

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

相关文章