如何根据用户输入重启我的java程序?

Jer*_*one 0 java

我正在编写一个用于计算小型企业员工总销售额的程序,并且正在尝试根据用户输入的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();



}
Run Code Online (Sandbox Code Playgroud)

}

Aif*_*ify 5

将所有代码放在一个说明的while循环中 while (yn.equalsIgnoreCase("y"))

别忘了把yn初始化为y!

二解决方案:

修改代码以使其返回字符串,如果用户输入y,则返回y,或者如果用户输入n,则返回n.将所有代码放在方法中(现在让我们称之为方法x)

public static void main(String[] args) {
    while(x().equalsIgnoreCase("y")){}
}
Run Code Online (Sandbox Code Playgroud)