Koneri
Koneri

Reputation: 297

Adding multiple numbers using java

I am trying to add numbers by scanning a line. I wanted the answer to be computed soon after i press "ENTER". What is the argument i should pass for the delimiter.

import java.io.*;
import java.util.*;
class add {
   public static void main(String[] args) throws IOException {
      int b=0;
      List<Integer> list  =  new ArrayList<Integer>();
      System.out.println("Enter the numbers");
      Scanner sc = new Scanner(System.in).useDelimiter(" ");
      while(sc.hasNextInt())
      {  
      list.add(sc.nextInt());
       }
      for(int i=0;i<list.size();i++) {
         b += list.get(i);
      }
      System.out.println("The answer is" + b);
   }
}

Upvotes: 0

Views: 5702

Answers (3)

StreamingBits
StreamingBits

Reputation: 137

import java.io.*;
import java.util.*;
class add {
   public static void main(String[] args) throws IOException {
      int b=0;
      List<Integer> list  =  new ArrayList<Integer>();
      System.out.println("Enter the numbers");
      Scanner sc = new Scanner(System.in).useDelimiter("[\r\n/]");
      while(sc.hasNextInt())
      {  
      list.add(sc.nextInt());

      }
      for(int i=0;i<list.size();i++) {
         b += list.get(i);
      }
      System.out.println("The answer is" + b);
   }
}

Upvotes: 0

jlordo
jlordo

Reputation: 37853

Simply write

Scanner sc = new Scanner(System.in);
while (sc.hasNextInt()) {
    list.add(sc.nextInt());
}

This will compute the result as soon as the first non integer is entered...


If you really only want to read one line of input, you need to do this:

Scanner sc = new Scanner(System.in);
String line = sc.nextLine();
for (String token : line.split("\\s+")) {
    list.add(Integer.parseInt(token));
}
// your for loop here...

Upvotes: 5

Mateusz
Mateusz

Reputation: 3048

You're adding one item to the list and then your condition for loop stop is i >= list.size(); and list.size() is 0. That's not what you want, you'd like to try

int amount = in.nextInt();
for (int i = 0; i < amount; i++)

Then you probably want to add items to list using list.add(in.nextInt());

Upvotes: 0

Related Questions