[英]How to use For Loop in Java to ask user for Input
这是我的作业:
编写一个模拟收银机的程序。 提示用户输入三个项目的价格。 将它们加在一起以获得小计。 确定小计的税(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();
}
}
}
为了给用户三倍的价格,我该怎么办?
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.
对于总数,您将需要其他变量。
我不会为您编写所有代码,但是可以使用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
}
您需要进行三个迭代,对于这种情况,最好使用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];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.