gpt4 book ai didi

java - 如何让我的哨兵脱离循环?

转载 作者:行者123 更新时间:2023-12-02 11:09:50 25 4
gpt4 key购买 nike

我想知道是否可以获得一些关于如何将我的哨兵排除在循环之外的反馈,这样它就不会被算作我的答案的一部分。我尝试在 while 循环中添加一个中断,但它只会弄乱我的公式。 (我想做的是让系统打印佣金的有效条目总数,并提供所有条目的总计)。谢谢

public class Commission {

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
NumberFormat nf = NumberFormat.getCurrencyInstance();

int salesPeople = 0;
double baseSalary = 200;
double sales = 0;
double salesTotal = 0;
double grandTotal = 0;
while (sales != -999) {
// ask for the amount of sales
System.out.println("Enter sales amount (enter -999 to end): ");
sales = scan.nextDouble();
salesPeople = salesPeople + 1;

// do the calculations
double noCommission = 0;
double lowCommission = ((sales - 500) * .03);
double mediumCommission = ((500 * .03) + ((sales - 1000) * .05));
double highCommission = ((500 * .03) + (2000 * .05) + ((sales - 3000) * .08));

double commission = 0;

if (sales < 500)
commission = noCommission;
else if (sales > 500 && sales < 1000)
commission = lowCommission;
else if (sales > 1000 && sales < 3000)
commission = mediumCommission;
else if (sales >= 3000)
commission = highCommission;

salesTotal = baseSalary + commission;
grandTotal = grandTotal + salesTotal;

System.out.println("You earned " + nf.format(commission)
+ " in commission for a total $" + salesTotal
+ " salary.\n");

}
if (sales == -999){
System.out.println("The number of employees is " + salesPeople
+ " and the total payout is " + grandTotal);
}

}

}

最佳答案

输入哨兵值后立即对其进行测试。您正在计算销售数量(而不是员工数量),我会限制变量范围(和蠕变)。比如,

Scanner scan = new Scanner(System.in);
NumberFormat nf = NumberFormat.getCurrencyInstance();
int salesCount = 0;
double grandTotal = 0, baseSalary = 200;
while (true) {
// ask for the amount of sales
System.out.println("Enter sales amount (enter -999 to end): ");
double sales = scan.nextDouble();
if (sales == -999) {
break;
}
salesCount++;
double commission = 0;
if (sales >= 500 && sales < 1000) {
commission = ((sales - 500) * .03);
} else if (sales >= 1000 && sales < 3000) {
commission = ((500 * .03) + ((sales - 1000) * .05));
} else if (sales >= 3000) {
commission = ((500 * .03) + (2000 * .05) + ((sales - 3000) * .08));
}

double salesTotal = baseSalary + commission;
grandTotal += salesTotal;

System.out.println("You earned " + nf.format(commission)
+ " in commission for a total $"
+ nf.format(salesTotal) + " salary.\n");
}
System.out.println("The number of sales is " + salesCount
+ " and the total payout is " + nf.format(grandTotal));

关于java - 如何让我的哨兵脱离循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50690727/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com