Win a copy of OCP Java SE 8 Programmer II Exam Study Guide this week in the OCP forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Multiple Lines of input at the same time?  RSS feed

 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello, I'm trying to figure out how to get multiple lines of input at the same time (without hitting enter every time).

Like so:

Sample Input:
10 12
10 14
100 200

Sample Output:
2
4
100



This is my code:

But it only takes input from one line, so I get this:

Input:
12 24 54 21 188 65

Output:
12
33
123



If I hit enter, it takes the input, so I can't move to a new line because it runs through the code. I have been looking through the Scanner API, but I can't work it out, how do I do it?

Thanks.
 
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If the input method is the same (enter two numbers, hit enter, enter two numbers, hit enter.....), you could still read them in one line. You only need to read ever pair of numbers. For example, lets say you have a line of numbers like this:
23 44 56 33 45 67 89 34
The only thing you need to do is read the line and then check every pair of numbers:
23 44
56 33
45 67
89 34

You can do that using many different methods. One way would be to parse the line as String and then split the numbers (using split method in String class) using space as delimiter. The split method will return an array of Strings, so the only thing you need to do read every two numbers of that array.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!