我是Java初學者,請耐心等待,不要因缺乏研究而判斷。在這裏我出多次循環的無效輸入後重新提示用戶
這個程序是基本的計算程序。它爲用戶設計計算項目的總成本。
我的程序調試正常,但問題是當用戶鍵入無效的條目。 一旦用戶鍵入無效的條目,for循環剛結束後Please, enter the amount!
我希望程序保持for循環,直到用戶鍵入一個有效的條目。
import java.util.Scanner;
public class icalculator {
public static void main(String[] args) {
Scanner Keyboard = new Scanner(System.in);
double cost, percentage;
int years;
System.out.println("What the estimate cost of the project?");
cost = Keyboard.nextDouble();
if (cost <= 0) {
System.out.println("Please, enter the amount!");
} else if(cost > 0) {
System.out.println("What the estimate percentage cost of the project? ");
percentage = Keyboard.nextDouble();
if (percentage <= 0) {
System.out.println("Please, enter the amount!");
} else if(percentage > 0) {
System.out.println("How long it will take to complete the project? \n"
+ "Please, enter whole numbers.");
years = Keyboard.nextInt();
if (years <= 0) {
System.out.println("Please, enter the amount!");
} else if (years > 0) {
這部分是計算區域:
double c = cost;
double p = percentage;
int y = years;
for (int i = 1; i <= 1; i++) {
c = Math.round(((p/100) * c) + y);
System.out.println("At " + percentage + "% rate, the cost of the project will be $"
+ c + " which take " + years + " years to be complete");
}
}
}
}
}
我在想,如果do while循環會更好,但我沒有試圖讓更多的complaicated那麼它是什麼節目。
目前尚不清楚你描述/觀察的實際問題是什麼。你能具體嗎? – David
@David當我運行該程序時,如果用戶鍵入無效的條目,程序將回答「請輸入數量!」,然後程序結束。我希望程序繼續執行for循環,直到用戶輸入有效的條目。 – krillavilla