Search code examples
javaadditionstringtokenizer

Cannot do the sum of numbers using a comma and string tokenizer


I have a program but I dont know specifically what my mistake is or how to fix it: The question is: Write a program that asks the user to enter a series of numbers separated by commas. The program should calculate and display the sum of all the numbers. For example, if I enter 4,5,6,7, the sum displayed should be 22.

This is what I have so far:

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);
    }
}

Thank you very much for the help.


Solution

  • Sum should be an int

    int sum = 0;
    

    Your for loop should be

    for (int i = 0; i < tokens.length; i++) {
          sum += Integer.parseInt(tokens[i]); 
    }