Java 无法使用逗号和字符串标记器进行数字求和

Java 无法使用逗号和字符串标记器进行数字求和,java,addition,stringtokenizer,Java,Addition,Stringtokenizer,我有一个程序,但我不知道我的错误是什么,也不知道如何解决:问题是: 编写一个程序,要求用户输入一系列以逗号分隔的数字。 程序应计算并显示所有数字的总和。 例如,如果输入4,5,6,7,则显示的总和应为22 这就是我到目前为止所做的: import java.util.Scanner; public class SumAll { public static void main(String[] args) { Scanner keyboard = new Scanne

我有一个程序,但我不知道我的错误是什么,也不知道如何解决:问题是: 编写一个程序,要求用户输入一系列以逗号分隔的数字。 程序应计算并显示所有数字的总和。 例如,如果输入4,5,6,7,则显示的总和应为22

这就是我到目前为止所做的:

import java.util.Scanner;

public class SumAll {

    public static void main(String[] args) {

        Scanner keyboard = new Scanner(System.in);

        String userNumber;
        String sum = null;

        //get numbers from user and store
        System.out.println("Enter numbers seperated by coma's: ");

        userNumber = keyboard.nextLine();
        String[] tokens = userNumber.split("[, ]");

        for (int i = 0; i < tokens.length; i++) {
            sum = tokens.length[i++]; //showing me error here. Its written array required but int //found. 
        }

        System.out.println("Sum is: " + sum);
    }
}
import java.util.Scanner;
公营速成速成速成速成速成速成速成速成速成速成速成速成速成速成速成速成速成速成速成速成速成速成速成速成速成速成速成速成速成速成速成速成速成速成速成速成速成速成速成速成速成速成速成速成速成{
公共静态void main(字符串[]args){
扫描仪键盘=新扫描仪(System.in);
字符串用户号;
字符串和=null;
//从用户和商店获取号码
System.out.println(“输入由coma分隔的数字:”);
userNumber=keyboard.nextLine();
String[]tokens=userNumber.split(“[,]”);
for(int i=0;i
非常感谢你的帮助

因为它应该是:

sum += Integer.parseInt(tokens[i]);
总和应该是整数

int sum = 0;
您的for循环应该是

for (int i = 0; i < tokens.length; i++) {
      sum += Integer.parseInt(tokens[i]); 
}
for(int i=0;i
这一行代码有几个地方不对劲

sum = tokens.length[i++];
  • 您不能像这样索引数组的
    长度。只需为数组编制索引(请参见下文)
  • for循环已在递增
    i
    。你不必再这样做了
  • 您需要将令牌转换为整数,然后才能将其添加到总和中
  • 您需要向总和中添加新值,而不是替换旧总和
  • 请尝试以下方法:

    sum += Integer.parseInt(tokens[i]);
    
    您还需要将
    sum
    设置为整数。而不是

    String sum = null;
    
    你需要

    int sum = 0;
    

    我知道我晚了两年多,但不久前我就开始学习Java,我想与大家分享我的解决方案。:)我使用了StringTokenizer类。我希望这对2017年及以后的人有所帮助

    import java.util.Scanner;
    import java.util.StringTokenizer;
    
    public class SumOfNumbersInString {
    
        public static void main(String[] args) {
    
            // Create a Scanner object
            Scanner keyboard = new Scanner(System.in);
    
            // Get user input
            System.out.print("Enter a series of numbers seperated by commas\n> ");
            String input = keyboard.nextLine();
    
            // Display sum by calling the getSum method
            System.out.println("SUM: " + getSum(input));
        }
    
        /**
         * 
         * @param input with the format --> (#,#,#,#)
         * @return sum of numbers in the input
         */
    
        public static int getSum(String input) {
    
            // Declare and initialize the sum accumulator variable
            int sum = 0;
    
            // Create a StringTokenizer object 
            // The string to be tokenized is passed as 1st parameter
            // The "," that separates tokens/numbers is the 2nd parameter
            StringTokenizer stringTokenizer = new StringTokenizer(input, ",");
    
            // The hasMoreTokens method of the StringTokenizer class returns true if there are more tokens left in the string
            // Otherwise, it returns false
            while (stringTokenizer.hasMoreTokens()) {
                // While the string has another token (number), parse the number to an integer and add its value to sum
                sum += Integer.parseInt(stringTokenizer.nextToken());
            }
    
            // Return sum's value to the method call
            return sum;
        }
    
    }
    
    输出

    Enter a series of numbers seperated by commas
    > 4,5,6,7
    SUM: 22
    

    /**@作者Jerry Urena**/

    public static void main(String[] args)     
    {
        String userinput;
        int total = 0;
    
        //keyboard function
        Scanner keyboard = new Scanner(System.in);   
    
        //Ask for input
        System.out.print("Please enter a series of numbers separated by commas " );
    
        //Get user input
        userinput = keyboard.nextLine();
    
        //Split numbers
        String[] numbers = userinput.split("[,]");
    
        //String loop
        for (String number : numbers) 
        {
            //Sum of numbers 
            total += Integer.parseInt(number); 
        }
    
        //Print results
        System.out.println("Total: " + total);          
    }    
    

    你不能用字符串做算术运算,你必须先把它们转换成数字。此外,正如编译器告诉您的,要访问
    标记的第i个元素,请使用
    标记[i]
    。最后,您在每个迭代中重新分配
    sum
    ,而不是添加到它。您已经在
    中为每个迭代的
    声明增加
    i
    。在
    sum=tokens[i++]中不需要额外的增量。此外,您在每次迭代中都覆盖了sum的值。它应该是
    sum+=tokens[i]