我有這一點的代碼返回到程序的開始,如果沒有預期的答案。Java -if else顯示多個輸出
...
else // returns to start for unsatisfactory
{
System.out.println();
System.out.println();
System.out.println("Check your spelling and try again");
main (args);
}
...
但是當我輸入不同的字,然後再次通過並進入預期字詞程序輸出兩個不同的結果
薪水:加薪$ 100.00
金額:$ 4.00
您的新薪水:$ 104.00
當前工資:$ 100.00
金額給自己加薪的:$ 0.00
你的新的工資:$ 100.00
我試圖用一個else if語句可能消除的一個原因,但它造成了同樣的事情。
import java.util.Scanner;
import java.text.NumberFormat;
public class Salary {
public static void main (String[] args) {
double currentSalary; // employee's current salary
double raise = 0.0; // amount of the raise
double newSalary; // new salary for the employee
String rating; // performance rating
Scanner scan = new Scanner(System.in);
System.out.print ("Enter the current salary: ");
currentSalary = scan.nextDouble();
System.out.print ("Enter the performance rating (Excellent, Good, or Poor): ");
rating = scan.next();
// Computes raise with if-else
if ((rating.equals("Excellent")) || (rating.equals("excellent"))) {
// calculates raise for excellent
raise = .06 * currentSalary;
}
else if ((rating.equals("Good")) || (rating.equals("good"))) {
// calculates raise for good
raise = .04 * currentSalary;
}
else if ((rating.equals("Poor")) || (rating.equals("poor"))) {
// calculates raise for poor
raise = .015 * currentSalary;
}
else {
// returns to start for unsatisfactory
System.out.println();
System.out.println();
System.out.println("Check your spelling and try again");
main (args);
}
newSalary = currentSalary + raise;
// Print the results
NumberFormat money = NumberFormat.getCurrencyInstance();
System.out.println();
System.out.println("Current Salary: " + money.format(currentSalary));
System.out.println("Amount of your raise: " + money.format(raise));
System.out.println("Your new salary: " + money.format(newSalary));
System.out.println();
}
}
不要調用主遞歸,而是使用while/for循環 – ravthiru
爲什麼不使用'equalsIgnoreCase'? – Li357
你可能想要寫一個體面的解析函數(不是'main')來驗證輸入。如果輸入無效,它可以返回false,在這種情況下,您可以調用另一個請求新輸入的函數(或者您想如何處理它)。我也是那種認爲用錯誤的輸入參數調用的程序最好不是全部開始的人。在這種情況下,如果用戶再次啓動程序並將其正確設置,則會更好。這並不總是成立(例如,如果輸入來自大型配置文件,例如需要修復),但通常這是一個好方法。 – patrik