这是我的任务:
编写一个模拟收银机的程序。提示用户输入三个项目的价格。将它们添加到一起以获得小计。确定小计的税(6%)。查找销售小计加税的总金额。显示每个项目的价格,小计金额,税额和最终金额。
我这样做了:
package cashregisteremulator;
import java.util.Scanner;
public class CashRegisterEmulator {
public static void main(String[] args) {
Scanner price = new Scanner(System.in);
System.out.print("Please enter a price for item number one $");
double price1 = price.nextDouble();
System.out.print("Please enter a price for item number two $" );
double price2 = price.nextDouble();
System.out.print("Please enter a price for item number three $");
double price3 = price.nextDouble();
double total = ((price1) + (price2) + (price3));
System.out.println("The subtotal is $" + total);
double tax = .06;
double totalnotax = (total * tax );
System.out.println("The tax for the subtotal is $" + totalnotax);
double totalplustax = (total + totalnotax);
System.out.println("The total for your bill with tax is $" + totalplustax);
}
}
但是,我需要使用循环进行此分配。由于提示只要求3次迭代,我想到了使用for循环。到目前为止,我有这个:
package CashRegister;
import java.util.Scanner;
public class CashRegister {
public static void main(String[] args) {
Scanner askPrice = new Scanner(System.in);
for(double i = 0 ; i < 3; i++);
{
System.out.println("Enter a value") ;
double price = askPrice.nextDouble();
}
}
}
为了向用户询问三次价格,我该怎么做?
答案 0 :(得分:1)
double sum = 0;
for(int i = ; i < n; i++)
{
//ask for value;
sum += value;
}
<强>更新强>
在你的更新中,这必须进入for循环:
double[] amount = new int[3];
for(int i = 0; i < amount.len; i++)
{
// ask user for value
amount[i] = value;
}
for(int i = 0; i < amount.len; i++)
{
// do your calculations and print it.
}
// print the total sums.
对于总计,您将需要额外的变量。
答案 1 :(得分:1)
我不打算为你编写所有代码,但这可以通过for循环轻松实现:
int numberOfIterations = 3;
// The format of the for loop:
// for (initialize counter; continuation condition; incrementer)
for(int i = 0; i < numberOfIterations; i++){
// do something
}
答案 2 :(得分:0)
您需要进行三次迭代,对于这种情况,最好使用的是 for循环。为了存储用户输入,您需要一个数组,其中存储 for循环中当前位置的索引的值。
看看我在你的代码上构建的这个例子:
double[] price= new double[3];
for (int i=0; i<3; i++); {
System.out.println("Enter another ");
double price[i] = price.nextDouble();
}
稍后,您可以对价格数组进行迭代,并添加所有值:
double total = 0.0;
for (int i=0; i<price.length; i++) {
total += price[i];
}