1

这是我的任务:

编写一个模拟收银机的程序。提示用户输入三件商品的价格。将它们加在一起以获得小计。确定小计的税 (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();



 }
}    
}

我要怎么做才能向用户索要三倍的价格?

4

3 回答 3

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.

对于总数,您将需要额外的变量。

于 2013-05-23T14:03:46.000 回答
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
}
于 2013-05-23T14:03:56.690 回答
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];
}
于 2013-05-23T14:03:13.767 回答