Java 如何读取一行数字并显示总和?

Java 如何读取一行数字并显示总和?,java,Java,我正在开发一个程序,它将读取整行数字,然后显示总和。它必须用java编写,并且必须尽可能简单。因此,没有什么比一些阵列或任何需要使其工作的东西更难的了 这是我想要的一个例子: Please enter some numbers with a space In between each. 12 34 7 93 4 This is the Sum of those numbers: 150 我已经尝试过很多次了,这就是我现在得到的 public static void main(String[]

我正在开发一个程序,它将读取整行数字,然后显示总和。它必须用java编写,并且必须尽可能简单。因此,没有什么比一些阵列或任何需要使其工作的东西更难的了

这是我想要的一个例子:

Please enter some numbers with a space In between each.
12 34 7 93 4
This is the Sum of those numbers: 150 
我已经尝试过很多次了,这就是我现在得到的

public static void main(String[] args) {
    Scanner kb = new Scanner(System.in);
    int numbers;
    int total;                  
    System.out.println("Please enter some numbers with a space between each");
    numbers = kb.nextInt();
    for(int i=args.length; i<numbers; i++) {
        System.out.println("The sum is " + numbers);
    }
}
publicstaticvoidmain(字符串[]args){
扫描仪kb=新扫描仪(System.in);
整数;
整数合计;
System.out.println(“请输入一些数字,每个数字之间留有空格”);
numbers=kb.nextInt();
对于(int i=args.length;i
Scanner#nextInt
只从输入流中读取一个
int
。相反,您希望读取一组数字并开始处理它们

我可以想出两种解决方案:

  • 读取整行(使用
    扫描仪#nextLine
    ),将其拆分为空格(
    “”
    )(使用
    字符串#拆分
    ),将每个
    字符串
    转换为
    整数
    ,并计算总和(使用
    整数#parseInt

  • 读取整行(使用
    Scanner#nextLine
    ),使用另一个
    Scanner
    读取存储在此
    字符串中的整数并计算总和

    int total = 0;
    System.out.println("Please enter some numbers with a space between each");
    String lineWithNumbers = kb.nexLine();
    Scanner lineScanner = new Scanner(lineWithNumbers);
    while (lineScanner.hasNext()) {
        total += lineScanner.nextInt();
    }
    

  • 我想要一个程序,让它在酒吧里…好吧,开始工作吧,没有什么能阻止你。如果你有问题,请以问题的形式发布在这里。我们不为你写免费代码。好吧,很抱歉。我已经尝试过很多次了,但现在我完全卡住了。这是我得到的,但它不能像我想要的那样工作。好吧,很高兴知道你做了些什么。请回答你的问题并提供你的尝试,然后我们可以帮助你解决你的具体问题。是的。好的,很抱歉现在这么做。我已经将nextLine更改为nextLine。既然我这样做了,我需要将我的两个Int更改为Strings@BenjaminMcIntyre是的,您还需要其他变量。您使用过数组吗以前?否则我需要提供另一个解决方案。不,我没有使用过数组。但是我需要了解它们,如果这样做的话,我会很乐意使用它们。非常感谢。我已经花了很多时间在它上面,但我只是无法使它工作。我现在要学习数组,看看它是否可以工作当我做这样的程序时,t将帮助我。非常感谢。哦,还有一个问题。如果它做同样的事情,那么很难做到这一点吗?但是当你输入数字时,让我们假设你也在其中输入了一个单词。程序只会跳过这个单词,省去它,只显示数字的总和
    int total = 0;
    System.out.println("Please enter some numbers with a space between each");
    String lineWithNumbers = kb.nexLine();
    Scanner lineScanner = new Scanner(lineWithNumbers);
    while (lineScanner.hasNext()) {
        total += lineScanner.nextInt();
    }