-3

So, this seems fairly simple bit of code.But when I run this, it gives me strange output. First, I store the number of elements of queries[] Array in NumQ variable.Then, I store the values of elements by looping from 0 to numQ-1.It works in any other case.

int numQ=sc.nextInt();
  String queries[]=new String[numQ];
    for(int i=0;i<numQ;i++){

        queries[i]=sc.nextLine();
    }
System.out.println(queries[0]);
System.out.println(queries[1]);
System.out.println(queries[2]);

In my case, inputs are-(note that it even doesn't ask for the value at index 2.numQ is 3)

enter image description here

And here is the output.

Output of the code

See, at queries[0], it stores blank value(blue selection is blank).At queries[ 1 ], it stores the first input(which was to be stored at index 0.And it stores the index 1 value at index 2 and so on.)

So what's the problem with my code. Thanks in advance:-)

LalaByte
  • 129
  • 9
  • When using a combination of `nextInt` and `nextLine`, beware there is still content in the buffer (ie the new line) which needs to be processed. Maybe use `nextLine` and use another `Scanner` on the result to get the `numQ` – MadProgrammer Apr 03 '17 at 05:34
  • I didn't notice it's a problem related with Scanners.And never saw that it's duplicate – LalaByte Apr 03 '17 at 05:36
  • If you type in 4 5 then press enter, it works. It's picking up the enter value, blank, and putting it in. – Nick Ziebert Apr 03 '17 at 05:37

1 Answers1

1

I suppose sc is a Scanner Object. The method nextInt() scan only int part before newline. So you have to use sc.nextLine() to skip the newline

int numQ=sc.nextInt();
sc.nextLine();

String queries[]=new String[numQ];
for(int i=0;i<numQ;i++){
    queries[i]=sc.nextLine();
}
System.out.println(queries[0]);
System.out.println(queries[1]);
System.out.println(queries[2]);
Ashraful Islam
  • 11,113
  • 3
  • 28
  • 48