如何在Java中正确格式化/嵌套while语句以验证输入数据类型和范围



//创建一个扫描程序对象以读取用户的输入扫描仪扫描=新扫描仪(System.in);

  //Asks the user for the month of birth 
  System.out.print("Enter your Month of Birth: ");
  //Utilizes a while loop to verify input type and prompt re-enter if necessary 
  while (!scan.hasNextInt()) 
  {
    System.out.print("Invalid data type: Please enter an Integer: ");
    scan.next();
  }
  //If input is correct type, uses the input 
  BirthMonth = scan.nextInt();
  //Utilizes the while loop to verify and ask user to re-enter month input if incorrect
  while (BirthMonth<1 || BirthMonth >12)
    {
      System.out.print("Invalid Month. Re-Enter your Month of Birth: ");
      BirthMonth = scan.nextInt();
    }

输入无效范围时会出现问题。程序会提示用户重新输入指定范围内的适当整数。如果用户在此时重新输入无效的数据类型(例如10),程序将崩溃。我相信发生这种情况是因为一旦验证了正确的数据类型,程序就会继续验证范围,而不会重新检查正确的数据种类。

我认为通过嵌套while语句可以很容易地解决这个问题,这样每次输入新的输入时,程序都会再次检查数据类型。我在正确格式化/嵌套while语句时遇到问题。有什么想法/提示吗?

你可以试试这个

int BirthMonth = 0; while (true) { if( (!scan.hasNextInt()) { System.out.print("Invalid data type: Please enter an Integer: "); scan.next(); } else { Birthmonth = scan.nextInt(); if(BirthMonth<1 || BirthMonth >12) { System.out.print("Invalid Month. Re-Enter your Month of Birth: "); scan.next(); } else break; } }

添加do和类似的东西

int BirthMonth = 1; // <-- should really be birthMonth
do { // <--
  if (BirthMonth != 1) {
    System.out.print("Invalid Month. Re-Enter your Month of Birth: ");
  }
  //Asks the user for the month of birth 
  System.out.print("Enter your Month of Birth: ");
  //Utilizes a while loop to verify input type and prompt re-enter if necessary 
  while (!scan.hasNextInt()) 
  {
    System.out.print("Invalid data type: Please enter an Integer: ");
    scan.next();
  }
  //If input is correct type, uses the input 
  BirthMonth = scan.nextInt();
  //Utilizes the while loop to verify and ask user to re-enter month input 
  //if incorrect
} while (BirthMonth<1 || BirthMonth >12); // <-- end it here.

最新更新