【问题标题】:How to loop a user input until integer is entered?如何循环用户输入直到输入整数?
【发布时间】:2020-08-15 15:03:52
【问题描述】:

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

我有以下代码:

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

如何为此创建一个循环?

【问题讨论】:

标签: java loops for-loop input while-loop


【解决方案1】:

让我们添加一个循环,将值作为字符串并检查它是否为数字:

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

【讨论】:

    【解决方案2】:

    试试这个

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

    【讨论】:

      【解决方案3】:

      尝试捕获异常并处理它,直到获得所需的输入。

      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]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-09-09
        • 1970-01-01
        • 2017-11-30
        • 2018-07-15
        • 1970-01-01
        • 1970-01-01
        • 2011-06-27
        相关资源
        最近更新 更多