0

I need to take input in the form of- Given 'n' number of boxes and each of these boxes may contain any number of distinct integers, So first user enters n,then for each value of i from 1 to n,I need to enter values till enter is pressed. I don't know how to do this, Eg-

5
1 2 3 4 5 6 7 8 9 
1 2
1 
4 5 6
3 4 5 6 7

I have tried this-

String str;
for(int i=0;i<n;i++)
{
    while(true)
    {
       str=scanner.next();
       if(str.isEmpty())
          break;
       int val=Integer.parseInt(str);
    }
}

Also tried str.equals("\n") and str.equals(""), But nothing is working. Somebody please help me out.Thanks.

Vivek kumar
  • 1,632
  • 1
  • 14
  • 29
  • You are only calling `scanner.next()` one time. You need to call it in each iteration of your loop otherwise `str` will only ever have one value. – Kelvin Sep 18 '16 at 19:13
  • http://stackoverflow.com/questions/5032356/using-scanner-nextline try scanner.readline - no need for customized checks – Patrick Sep 18 '16 at 19:13
  • use str.equalsIgnoreCase("") instead of str.isEmpty() – halim Sep 28 '16 at 13:01

4 Answers4

1

Try something like this:

int n = scanner.nextInt(); 
for(int i=0;i<n;i++)
{
    String str = scanner.nextLine();
    String[] array = str.split(" ");
}

You take a String from user (a single line of numbers) and you split it by space, so you have all the numbers as String in the array. Then you have to parse them to int or do whatever you want with them.

Shadov
  • 5,061
  • 2
  • 16
  • 27
1

try this

String str;
for(int i=0;i<n;i++)
{
    while(true)
   {
   str=scanner.next();
   if(!str.equalsIgnoreCase(""))
      break;
   int val=Integer.parseInt(str);
   }
 }
halim
  • 211
  • 1
  • 10
0

In Scanner class has next(){only take input upto any white space character occur} nextLine(){ takes input upto new line character }

Try with nextLine() method and then try to store in any array Using n value.Then you can use split or string tokenzer function and then we extract integer from in it

0

This worked for me

while (true) {
    String str = sc.nextLine();
    if (str.equalsIgnoreCase("")) break;                        
}
Brahmaji
  • 1
  • 2