public class lsjdflsjdf {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int input, sum = 0, count = 0;
System.out.print("Enter a positive integer number: ");
input = s.nextInt();
while (input != -1) {
count++;
sum += input;
System.out.print("Enter a positive integer number: ");
input = s.nextInt();
}
System.out.println("Entered Number:\t" + count);
System.out.println("The Sum:\t\t" + sum);
}
}
How do I take all the inputs so they can be displayed in the "Entered Number" println statement at the end so it would display such as:
如何获取所有输入,以便它们可以显示在最后的“输入数字”println语句中,以便显示如下:
Entered Number: 10, 2, 13, 50, 100
The Sum: 175
Entered Number: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
The Sum: 48
Entered Number: 1, 1, 1, 1, 100
The Sum: 104
Entered Number: 0, 0, 0, 0, 0, 100
The Sum: 100
1 个解决方案
#1
0
Get rid of count and replace it with a String
which will report the numbers that have been entered. A simplistic solution would be to concatenate the new inputs with the existing output in your while loop.
摆脱计数并用一个字符串替换它,该字符串将报告已输入的数字。一个简单的解决方案是将新输入与while循环中的现有输出连接起来。
For example:
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int input, sum = 0;
System.out.print("Enter a positive integer number: ");
input = s.nextInt();
String outputString = ""; //our result string
while (input != -1) {
outputString += input + " "; //adding to the output string
sum += input;
System.out.print("Enter a positive integer number: ");
input = s.nextInt();
}
System.out.println("Entered Number:\t" + outputString);
System.out.println("The Sum:\t\t" + sum);
}
You could also use StringBuilder to build up your output String
.
您还可以使用StringBuilder来构建输出String。
#1
0
Get rid of count and replace it with a String
which will report the numbers that have been entered. A simplistic solution would be to concatenate the new inputs with the existing output in your while loop.
摆脱计数并用一个字符串替换它,该字符串将报告已输入的数字。一个简单的解决方案是将新输入与while循环中的现有输出连接起来。
For example:
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int input, sum = 0;
System.out.print("Enter a positive integer number: ");
input = s.nextInt();
String outputString = ""; //our result string
while (input != -1) {
outputString += input + " "; //adding to the output string
sum += input;
System.out.print("Enter a positive integer number: ");
input = s.nextInt();
}
System.out.println("Entered Number:\t" + outputString);
System.out.println("The Sum:\t\t" + sum);
}
You could also use StringBuilder to build up your output String
.
您还可以使用StringBuilder来构建输出String。