简体   繁体   English

如何根据用户输入重新启动Java程序?

[英]How can I restart my java program based on user input?

I'm writing a program used to calculate the total sales of employees in a small business, and am trying to figure out how to restart the program based on a user input of y/n. 我正在编写一个用于计算小型企业中员工总销售额的程序,并试图根据用户输入的y / n找出如何重新启动该程序。 I know that loops are what I need to use here, but need a push in the right direction. 我知道循环是我在这里需要使用的,但是需要朝着正确的方向推进。

Code: 码:

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();



}

} }

Put all the code inside a while loop that says while (yn.equalsIgnoreCase("y")) 将所有代码放入一个while循环中, while (yn.equalsIgnoreCase("y"))

Don't forget to initialize yn to y! 不要忘记将yn初始化为y!

Second solution: 第二种解决方案:

Modify the code so that it returns a string, and if the user inputs y, return y, or if the user inputs n, return n. 修改代码,使其返回字符串,如果用户输入y,则返回y,或者如果用户输入n,则返回n。 Put all that code inside a method (lets call it method x for now) 将所有代码放入方法中(现在将其称为方法x)

public static void main(String[] args) {
    while(x().equalsIgnoreCase("y")){}
}

Using a do-while loop (while loop should have the same effect) and ask for (y/n) at the end. 使用do-while循环(while循环应具有相同的效果),最后要求(y / n)。

Like this: 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")); String yn; do { // Your code here // Ask for confirmation } while (yn.equals("y"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM