0

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

3 Answers 3

5

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...
Sign up to request clarification or add additional context in comments.

9 Comments

Koneri said: I wanted the answer to be computed soon after i press enter. Your Scanner won't stop when user press enter.
What do you mean by soon ?
@kocko I think Koneri means as soon as.
I think he means "when", so this is a valid answer :)
@kocko i tried that already. it still waits for '/'(basically any character apart from integer to mark as end of inputs) to compute the result
|
0

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

Comments

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

1 Comment

use the argument "[\r\n/]" as it is the carriage return character

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.