[英]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.