这是我的代码:
import java.util.*;
public class InputSum
{
public static void main(String[]args)
{
Scanner input = new Scanner(System.in);
System.out.print("Please enter integer values (-1 to to display numbers & sum): ");
int i = input.nextInt();
int j = 0;
while (i != -1)
{
j += i;
i = input.nextInt();
}
System.out.println("Entered Number: " + i);
System.out.println("The Sum: " + j);
}
}
截至目前,我的输出是:
输入数字:-1
总和:(输入数字的总和)
答案 0 :(得分:2)
在循环中打印它们:
while (i != -1)
{
System.out.println("Entered Number: " + i);
j += i;
i = input.nextInt();
}
System.out.println("The Sum: " + j);
或者您想要将它们打印在一行中:
List numbers = new ArrayList<Integer>();
while (i != -1)
{
numbers.add(i);
j += i;
i = input.nextInt();
}
System.out.println("Entered Numbers: " + numbers);
System.out.println("\nThe Sum: " + j);
答案 1 :(得分:0)
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Integer> numbers = new ArrayList<Integer>();
System.out
.print("Please enter integer values (-1 to to display numbers & sum): ");
int i = input.nextInt();
int j = 0;
while (i != -1) {
numbers.add(i);
j += i;
i = input.nextInt();
}
System.out.println("Entered Numbers: ");
for (int a = 0; a < numbers.size(); a++) {
System.out.print(" " + numbers.get(a));
}
System.out.println("The Sum: " + j);
}
这应该可以打印数字。您可以使用arraylist来存储数字,然后如果您需要它们以供以后计算,它们仍然存储在arraylist中。
答案 2 :(得分:0)
package net.rajkannan.stackoverflow;
import java.util.*;
public class InputSum {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out
.print("Please enter integer values (-1 to to display numbers & sum): ");
int i = input.nextInt();
int j = 0;
String numbers = "";
while (i != -1) {
j += i;
numbers = numbers + i + " ";
i = input.nextInt();
}
System.out.println("Entered Numbers: " + numbers);
System.out.println("The Sum: " + j);
}
}