[英]How to print all inputs used from loop
I am trying to have an output where the entered numbers in the loop are all printed out as separate numbers.我试图有一个输出,其中循环中输入的数字都作为单独的数字打印出来。 Example: Entered numbers: 10, 15, 1, 25 .示例:输入的数字: 10, 15, 1, 25 。
Here is my code:这是我的代码:
import java.util.Scanner;
public class SumofNumbersAbove0 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int number = 0;
int input;
for (input = 0; input >= 0;) {
number = number + input;
System.out.print("Enter number: ");
input = scan.nextInt();
}
System.out.println("Entered Number: " + input);
System.out.println("The sum: " + number);
}
}
I get the sum of all the numbers correctly.我正确地得到了所有数字的总和。 But all I get for entered numbers is the final one.但我对输入的数字所得到的只是最后一个。
Move your print of input
into the loop where each value of input
is actually present.将您的input
打印移动到实际存在每个input
值的循环中。 Where you have it you only get the last input
在你拥有它的地方,你只能得到最后的input
for (input = 0; input >= 0;) {
number = number + input;
System.out.print("Enter number: ");
System.out.println("Entered Number: " + input);
input = scan.nextInt();
}
System.out.println("The sum: " + number);
Issue: In your code the two variables you have input
and number
(which should rather be named sum) are solving very different purpose.问题:在您的代码中,您input
的两个变量和number
(应该命名为 sum)正在解决非常不同的目的。 input
is acting a transient pedestrial where the user-entered values come and land. input
是一个短暂的行人,用户输入的值来了。 From there the value is added into number
and then come another user-entered value which lands onto the same pedestrial thereby knocking-off the previous value.从那里,该值被添加到number
,然后是另一个用户输入的值,该值落在同一个基座上,从而取消了之前的值。
Thus when you print input
at the bottom of your code, the value you find is the one which came last to the pedestrial (which in your case is some integer < 0)因此,当您在代码底部打印input
时,您找到的值是最后一个到达 pedestrial 的值(在您的情况下是某个整数 < 0)
Solution: What you want is to perform an operation (print) on each of the input values.解决方案:您想要的是对每个输入值执行操作(打印)。 You can do either of the following-您可以执行以下任一操作-
number
is another operation you are already doing before losing the value将值添加到number
是您在丢失值之前已经在执行的另一项操作number
could be another.打印它们可能是一个操作,将它们的值累加到另一个变量number
可能是另一个操作。Hope that helps希望有帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.