我已经问类似的问题之前:String while loop,但现在我还有一个问题,我想不通......字符串while循环部分2
double bill = 0.0;
double tip = 0.0;
// Taking an input
System.out.print("Please enter the total amount of your bill > ");
String strBill = scan.nextLine();
boolean validatedBill = false;
// Validating Bill
while(!validatedBill) {
try {
bill = Double.parseDouble(strBill);
validatedBill = true;
} catch(NumberFormatException e) {
System.out.print("Enter a valid number > ");
strBill = scan.nextLine();
} // end of catch block
} // end of while loop
while(bill < 0) {
System.out.print("Your bill amount is less then 0, try again > ");
bill = scan.nextDouble();
} // end of while loop
System.out.print("Please enter the tip percentage > ");
String strTip = scan.nextLine();
boolean validatedTip = false;
// Validating Tip
while(!validatedTip) {
try {
tip = Double.parseDouble(strTip);
validatedTip = true;
} catch(NumberFormatException e) {
System.out.print("Enter a valid tip percentage > ");
strTip = scan.nextLine();
} // end of catch block
} // end of while loop
while(tip < 0) {
System.out.print("Your tip is below 0, try again > ");
tip = scan.nextDouble();
} // end of while loop
我输入运行完美,但是当程序要求我输入我的小费百分比,它让我这样说:
请所有一行进入尖百分比>输入有效的尖端百分比>
但与此同时它正常工作和程序可以验证字符串和数字。
的代码应该以这种方式工作: 1.请输入您的账单总金额> 2.请输入尖端百分比>
非常感谢!
固定码
double bill = 0.0;
double tip = 0.0;
// Taking an input
System.out.print("Please enter the total amount of your bill > ");
String strBill = scan.nextLine();
boolean validatedBill = false;
// Validating Bill
while(!validatedBill) {
try {
bill = Double.parseDouble(strBill);
validatedBill = true;
} catch(NumberFormatException e) {
System.out.print("Enter a valid number > ");
strBill = scan.nextLine();
} // end of catch block
} // end of while loop
while(bill < 0) {
System.out.print("Your bill amount is less then 0, try again > ");
bill = scan.nextDouble();
} // end of while loop
scan.nextLine();
System.out.print("Please enter the tip percentage > ");
String strTip = scan.nextLine();
boolean validatedTip = false;
// Validating Tip
while(!validatedTip) {
try {
tip = Double.parseDouble(strTip);
validatedTip = true;
} catch(NumberFormatException e) {
System.out.print("Enter a valid tip percentage > ");
strTip = scan.nextLine();
} // end of catch block
} // end of while loop
while(tip < 0 || tip > bill) {
System.out.print("Your tip is less then 0 or greater then your bill, try again > ");
tip = scan.nextDouble();
} // end of while loop
您可能需要使用''方法println()的,而不是'打印()'。 –
您是否尝试过使用system.out.println() – KVK
在'System.out.print(“请输入提示百分比>”);';'之前加'scan.nextLine();''。 'nextDouble()'读取一个令牌,所以有一条线用'nextLine()'留下,你使用同一行而不是nextline – silentprogrammer