File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Scanner Class Doubt

 
Sanjeev Narula
Greenhorn
Posts: 19
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1. import java.util.*;
2. class Brain {
3. public static void main(String[] args) {
4. // insert code block here
5. }
6. }

Which, inserted independently at line 4, compile and produce the output
"123 82"?
(Choose all that apply.)
A. Scanner sc = new Scanner("123 A 3b c,45, x5x,76 82 L");
while(sc.hasNextInt()) System.out.print(sc.nextInt() + " ");
B. Scanner sc = new Scanner("123 A 3b c,45, x5x,76 82 L").
useDelimiter(" ");
while(sc.hasNextInt()) System.out.print(sc.nextInt() + " ");
C. Scanner sc = new Scanner("123 A 3b c,45, x5x,76 82 L");
while(sc.hasNext()) {
if(sc.hasNextInt()) System.out.print(sc.nextInt() + " ");
else sc.next(); }
D. Scanner sc = new Scanner("123 A 3b c,45, x5x,76 82 L").
useDelimiter(" ");
while(sc.hasNext()) {
if(sc.hasNextInt()) System.out.print(sc.nextInt() + " ");
else sc.next(); }
E. Scanner sc = new Scanner("123 A 3b c,45, x5x,76 82 L");
do {
if(sc.hasNextInt()) System.out.print(sc.nextInt() + " ");
} while ( sc.hasNext() );
F. Scanner sc = new Scanner("123 A 3b c,45, x5x,76 82 L").
useDelimiter(" ");
do {
if(sc.hasNextInt()) System.out.print(sc.nextInt() + " ");
} while ( sc.hasNext() );


Answer is A and C

Can any one explain how ?
Thanks in advance.
 
Srinivasan thoyyeti
Ranch Hand
Posts: 557
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
please find the reply here,

http://www.coderanch.com/t/262215/java-programmer-SCJP/certification/Scanner
 
Louis Moloney
Ranch Hand
Posts: 59
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A is incorrect

A will produce 123 only.
 
Sanjeev Narula
Greenhorn
Posts: 19
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi

Regarding C option why did not it also prints other integers like 3 45 5 76
 
Srinivasan thoyyeti
Ranch Hand
Posts: 557
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Sanjeev,

I have clearly described in my first reply ...

By default Scanner splits given string using " ".
Which ever tokens are integers they will only be displyed.

you can't expect ex: x42y to be displayed as 42.

All the best
 
Sanjeev Narula
Greenhorn
Posts: 19
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Srinivasan .Now i am having better understanding of Scanner Class.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic