循环时的字符串

时间:2016-02-04 14:31:26

标签: java string try-catch java.util.scanner

我需要检查用户是否输入数字(双精度)或字符串,除最后一部分外,一切都很完美。如果用户输入" hello",程序将要求输入有效数字,但它无法正常工作。它给了我一个无限循环,除非我进入空间" "

这是我的代码:

double bill = 0.0;
System.out.print("Please enter the total amount of your bill > ");
  String strAmount = keysIn.nextLine();
  try {
    bill = Double.parseDouble(strAmount);
    while (bill < 0) {
        System.out.print("Your bill amount is less then 0, try again > ");
        bill = keysIn.nextDouble();
      }
  } catch(NumberFormatException e) {
      while (!strAmount.isEmpty()) {
        System.out.print("Enter a valid number > ");
        strAmount = keysIn.nextLine();
      }
  }

感谢。

4 个答案:

答案 0 :(得分:0)

你有两个while循环检查不同的条件。 试试这个:

double bill = 0.0;
System.out.print("Please enter the total amount of your bill > ");
String strAmount = keysIn.nextLine();
String numberString = strAmount.trim();

boolean invalidNumber = false;

 try {
   bill = Double.parseDouble(numberString);
 } catch(NumberFormatException e) {
   Systeout.print("Enter a valid number...");
   invalidNumber = true;
 }



while (bill < 0) {
    if(invalidNumber){
        System.out.print("Enter a valid number...");
    } else {
        System.out.println("Your bill amount is less then 0, try again...");
    }
    strAmount = keysIn.nextLine();
    numberString = strAmount.trim();

    try {
        bill = Double.parseDouble(numberString);
        invalidNumber = false;
    } catch(NumberFormatException e) {
        invalidNumber = true;
    }
  }

}

答案 1 :(得分:0)

您的无限循环归因于while (!strAmount.isEmpty()),这意味着只要strAmount 为空,它就会循环播放,因此删除!并移动检查循环结束。

        do {
            System.out.print("Enter a valid number > ");
            strAmount = keysIn.nextLine();
        } while (strAmount.isEmpty());

答案 2 :(得分:0)

你可以试试这个:

double bill = 0.0;
    System.out.print("Please enter the total amount of your bill > ");
      String strAmount = keysIn.nextLine();
      boolean validated = false;

      //Validate
      while(!validated){
          try{
              bill = Double.parseDouble(strAmount);
              validated = true;
          }
          catch(NumberFormatException e) {
              System.out.print("Enter a valid number > ");
              strAmount = keysIn.nextLine();
          }
      }

      //Continue...
      while (bill < 0) {
        System.out.print("Your bill amount is less then 0, try again > ");
        bill = keysIn.nextDouble();
      }

答案 3 :(得分:0)

一直尝试使用Scanner.nextDouble()而不是一次。它只接受双打。

double bill = 0.0;
System.out.print("Please enter the total amount of your bill > ");
bill = keysIn.nextDouble();
while (bill < 0) {
    System.out.print("Your bill amount is less then 0, try again > ");
    bill = keysIn.nextDouble();
}