[英]Asking User Multiple Times for Input in Java
So far I have this: 到目前为止,我有这个:
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();
}
}
}
How can I prompt the user for three values and add them together? 如何提示用户输入三个值并将它们添加在一起?
Take a look at this example I built on your code: 看看这个基于您的代码的示例:
double[] price= new double[3];
for (int i=0; i<3; i++) {
System.out.println("Enter another ");
double price[i] = askPrice.nextDouble();
}
Later on, you can iterator over the price array, and add all the values: 稍后,您可以迭代价格数组,并添加所有值:
double total = 0.0;
for (int i=0; i<price.length; i++) {
total += price[i];
}
seems like a homework . 好像是作业。 So just a hint here. 所以这里只是一个提示。 Try to learn and do by yourself with the help 在帮助下尝试学习和自己做
To calculate the sum you need to declare a variable out of the for loop scope. 要计算总和,您需要在for循环范围之外声明一个变量。 so declare a variable say sum and after each input add price to sum. 因此,声明一个变量,例如sum,然后在每次输入后将价格加到sum上。 After the end of loop the sum will containt the result. 循环结束后,总和将包含结果。
Edit: 编辑:
we all missed a minor thing.. You placed a semicolon (;) after for loop remove this.. 我们都错过了一件小事。.您在for循环后放置了分号(;),然后将其删除。
so use 所以用
for(double i = 0 ; i < 3; i++)
instead of 代替
for(double i = 0 ; i < 3; i++);
As you have used semicolon the for loop has a blank statement. 使用分号时,for循环具有空白语句。 So your input is not in the scope of for loop. 因此,您的输入不在for循环的范围内。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.