gpt4 book ai didi

java - 编写 for 循环/while 循环?

转载 作者:行者123 更新时间:2023-12-01 23:12:16 26 4
gpt4 key购买 nike

我在高中的编程课上,我的作业是制作一个基本的小计和顶级计算器,但我在一家餐馆工作,所以制作一个只能让你在一种食物中读到。因此,我尝试让它能够接收多种食品并将它们添加到一个价格变量中。抱歉,如果某些代码可能看起来效率低下或冗余。当然这只是高中。

问题是,当我运行它时,它会询问用户是否想要添加其他食品,当我输入"is"或“否”时,程序什么也不做。继续奔跑,但不再前进。有什么解释吗?

import java.text.NumberFormat;
import java.util.Scanner;

public class Price {

/**
* @param args
*/
public static void main(String[] args) {

final double taxRate = .0887; //8.87% Tax Rate
double tipRate;
int quantity1;
Scanner kb = new Scanner(System.in);
double subtotal, tax, tip, totalCost1, unitPrice1 = 0;
String done;

System.out.println ("How many of the first item did you get?: ");
quantity1 = kb.nextInt();

for (int i = 0; i < quantity1; i++)
{
System.out.println ("What was the price of that single item "+(i+1) + ": ");
unitPrice1 = kb.nextDouble();

System.out.println ("Was there another food item you'd like to add?: ");
done=kb.next();
while (done.equalsIgnoreCase("Yes"));
}

System.out.println ("What percent would you like to tip? (Formatted like 0.10 for 10%, 0.20 for 20%, etc.): ");
tipRate = kb.nextDouble();

subtotal= quantity1 * unitPrice1;
tax = subtotal * taxRate;
totalCost1 = subtotal + tax;
tip = totalCost1 * tipRate;
totalCost1 = totalCost1 + tip;


//Formatting
NumberFormat money = NumberFormat.getCurrencyInstance();
NumberFormat tipMoney = NumberFormat.getCurrencyInstance();
NumberFormat taxPercent = NumberFormat.getPercentInstance();
NumberFormat tipPercent = NumberFormat.getPercentInstance();


System.out.println ("Your total before tax is: " + money.format(subtotal));
System.out.println ("The tax is " + money.format(tax) + " at " + tipPercent.format(taxRate));
System.out.println ("The tip at " + tipPercent.format(tipRate) + " is " + tipMoney.format(tip));

}

}

最佳答案

这里有一个无限循环:

while (done.equalsIgnoreCase("Yes"));

输入 Yes 后,它会继续坐在那里什么都不做,因为 done 的值是 Yes并且永远不会改变。

而且你的循环结构有点奇怪。您的外for循环运行的次数与第一项的数量相同。但您不应该只将该数字乘以成本吗?因为您要么运行循环与用户输入的项目数一样长(通过预先询问他们),要么您不询问他们项目总数,而只是要求他们输入 Yes如果他们想添加更多项目;你实际上无法两者兼得。

你的循环可能看起来像这样:

String input = "Yes";
while(input.equalsIgnoreCase("Yes")) {
System.out.println ("How many of the first item did you get? ");
quantity1 = kb.nextInt();

System.out.println ("What was the price of that single item? ");
unitPrice1 = kb.nextDouble();

//total += unitPrice1 * quantity1 - you don't have this in your code, but this is where you would be calculating the running total

System.out.println("Was there another food item you'd like to add? ");
input = kb.next();
}

关于java - 编写 for 循环/while 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21734139/

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