字符串while循环 [英] String while loop

查看:67
本文介绍了字符串while循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检查用户是否输入数字(双精度)或字符串,除最后一部分外,其他所有内容均正常运行.如果用户输入"hello",程序将要求输入有效的号码,但不能正常工作.除非我输入空格",否则它将给我一个无限循环.

I need to check if the user enter a number(double) or string, everything works perfect except the last part. If the user enters "hello", the program will ask to enter the valid number but it doesn't work properly. It gives me an infinite loop unless I will enter space " ".

这是我的代码:

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

谢谢.

推荐答案

尝试始终使用Scanner.nextDouble()而不是一次.它只会接受Doubles.

Try using Scanner.nextDouble() all the time instead of once. It will only accept Doubles.

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

这篇关于字符串while循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆