我正在编写一个程序,用于计算小型企业员工的总销售额,并且正在尝试根据用户输入的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();
}
}
答案 0 :(得分:5)
将所有代码放在一个名为while (yn.equalsIgnoreCase("y"))
不要忘记将yn初始化为y!
第二个解决方案:
修改代码以使其返回字符串,如果用户输入y,则返回y,或者如果用户输入n,则返回n。 将所有代码放在方法中(暂时将其称为方法x)
public static void main(String[] args) {
while(x().equalsIgnoreCase("y")){}
}
答案 1 :(得分:0)
使用do-while循环(while循环应具有相同的效果)并在最后请求(y / n)。
像这样:
String yn;
do
{
// Your code here
// Ask for confirmation
}
while (yn.equals("y"));