【发布时间】:2014-03-25 22:09:01
【问题描述】:
试图弄清楚我将如何从用户那里获取任意数量的输入数字并将它们加在一起
用户输入示例:1 2 3 4 总和 = 10
用户可以将任意数量的数字放在不指定的数量中,所以如果他想添加 1 2 3 4 5 6 7 8 9 10 11 12 13,那么它们的总和就是 91
提前感谢您的帮助。
import java.util.Scanner;
public class test
{
public static final int SENTINEL = -1;
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
int score = 0;
int sum = 0;
System.out.println("Enter numbers here");
while (score >= 0) {
if (score <= -1) {
score = kb.nextInt();
sum += score;
score = 0;
}
System.out.println(sum);
}
}
}
感谢 libik 的所有时间和帮助,这是完成的代码。
import java.util.Scanner;
public class JavaApplication1156 {
public static void main(String[] args) {
System.out.println("Enter numbers here");
int sum;
do {
Scanner kb = new Scanner(System.in);
int score = 0;
sum = 0;
String line = kb.nextLine();
kb = new Scanner(line); //has to do this to make the kb.hasNexInt() work.
while (kb.hasNextInt()) {
score = kb.nextInt();
sum += score;
}
if (sum <= -1)
System.out.println("Application ended");
else if (sum >= 0)
System.out.println("Sum = " + sum);
} while (sum != -1);
}
}
【问题讨论】:
-
请显示您尝试解决问题的任何代码,以及您可能遇到的任何问题,然后您将获得一些指导。但是,我们不会为您完成(家庭)工作。
-
查看 Java 中的 Scanner 类以获取标准输入。 docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
-
不错的类名 :D :D
-
@rgettman 按要求添加了我的代码,也不是作业,而是做一些额外的事情,因为我对数字做的最后一件事是从 diff int 添加输入数据,但感谢您的回复。另外我遇到的问题是在第一个输入示例 123 123 将返回 123 而不是 246 之后没有读取任何数字。
-
@libik LOL 抱歉,我从 Lab 20 复制了大部分代码,这比 Lab 19 容易得多,我很生气,忘记更改了哈哈。最后也只是从我复制的东西中删除了所有代码并重写了它。
标签: java sum user-input