[英]How can I restart my java program based on user input?
我正在編寫一個用於計算小型企業中員工總銷售額的程序,並試圖根據用戶輸入的y / n找出如何重新啟動該程序。 我知道循環是我在這里需要使用的,但是需要朝着正確的方向推進。
碼:
import java.util.Scanner;
public class calcMain {
public static void main(String[]args){
double totalPay = 0, itemOne = 239.99, itemTwo = 129.75, itemThree = 99.95, itemFour = 350.89, commission;
int weeklyBonus = 200, numSold;
String employee1, employee2, employee3, employee4, yn;
Scanner kb = new Scanner(System.in);
System.out.println("Please enter the salesperson's name: ");
employee1 = kb.nextLine();
System.out.println("Please enter the number of Item 1 sold: ");
numSold = kb.nextInt();
totalPay += (itemOne * numSold);
System.out.println("Please enter the number of Item 2 sold: ");
numSold = kb.nextInt();
totalPay += (itemTwo * numSold);
System.out.println("Please enter the number of item 3 sold: ");
numSold = kb.nextInt();
totalPay += (itemThree * numSold);
System.out.println("Please enter the number of item 4 sold: ");
numSold = kb.nextInt();
totalPay += (itemFour * numSold);
System.out.println("The total weekly earnings for " +employee1+ " are: " +totalPay);
System.out.println("Would you like to input the sales of another employee? (y/n)");
yn = kb.next();
}
}
將所有代碼放入一個while循環中, while (yn.equalsIgnoreCase("y"))
不要忘記將yn初始化為y!
第二種解決方案:
修改代碼,使其返回字符串,如果用戶輸入y,則返回y,或者如果用戶輸入n,則返回n。 將所有代碼放入方法中(現在將其稱為方法x)
public static void main(String[] args) {
while(x().equalsIgnoreCase("y")){}
}
使用do-while循環(while循環應具有相同的效果),最后要求(y / n)。
像這樣: String yn; do { // Your code here // Ask for confirmation } while (yn.equals("y"));
String yn; do { // Your code here // Ask for confirmation } while (yn.equals("y"));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.