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

时间:2014-10-14 02:51:41

标签: java loops nested

//创建一个扫描程序对象以读取用户的输入       扫描仪扫描=新扫描仪(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();
    }

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

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

2 个答案:

答案 0 :(得分:0)

添加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.

答案 1 :(得分:0)

您可以尝试这样

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