siuxoes
siuxoes

Reputation: 13

Adding numbers from a string without using split Java

I want to add the numbers from a user input, String. I know I can do it by using split function like this:

import java.util.Scanner;
public class MyClass{
    public static void main(String[] args){
        String[] Numbers = in.nextLine().split(" ");
        int sum = 0;
        for (String s : Numbers) {
            sum += Integer.parseInt(s);
        }
    }
}

Lets assume that the user input is: "1 2 3 4 5" the sum will be sum=15.

Ok, now I want to do it but without using arrays and the split().

A friend told me about using Scanner.hasNext() Method, but I cannot make it work

Upvotes: 1

Views: 812

Answers (1)

Jens
Jens

Reputation: 69440

Try this:

import java.util.Scanner;
public class MyClass{
    public static void main(String[] args){
        int sum = 0;
        Scanner in = new Scanner(System.in);
        while (in.hasNextInt()){
            sum += in.nextInt();
        }
    }
}

Upvotes: 3

Related Questions