Java OCA OCP Practice Question 2897

Question

Given the proper imports, and given:

23.  String s = "123 222222 x 345 -45";  
24.  Scanner sc = new Scanner(s);  
25.  while(sc.hasNext())  
26.    if(sc.hasNextShort())  
27.      System.out.print(sc.nextShort() + " "); 

What is the result?

  • A. The output is 123 345
  • B. The output is 123 345 -45
  • C. The output is 123 222222 345 -45
  • D. The output is 123 followed by an exception.
  • E. The output is 123 followed by an infinite loop.


E is correct.

Note

In the first while loop iteration a short is found, printed, AND the nextShort() method moves the scanner to the next token.

When the second (through nth) iteration of the while executes, the token 222222 is found, which is not a short, so the program never moves to the third token.

If line 28 read "else sc.next();", then non- short tokens would be "consumed" and the scanning would proceed to produce answer B.




PreviousNext

Related