Reputation: 297
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
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
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
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