我已經問類似的問題之前: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