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:
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
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.
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
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.