• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

scjp page 506 question 14 doubt

 
Ranch Hand
Posts: 188
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
package sdm;

import java.util.Scanner;

public class Brain {
public static void main(String args[]) {
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();

}
}
}
/**** Doubt**************/

why is the output 123 82 when we have other numbers in between
 
author
Posts: 9050
21
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hey Prasanna,

We're always trying to improve the book, so I'd be interested in knowing if you understood the discussion on pages 487-489? If not, where did you get lost?

Thanks,

Bert
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Scanner breaks the input up into tokens separated by spaces. So the string "123 A 3b c,45,x5x,76 82 L" is split up into:

123
A
3b
c,45,x5x,76
82
L

Of those, only 123 and 82 are numbers. So sc.hasNextInt() will only return true for those tokens, and false for the other tokens.
 
pras
Ranch Hand
Posts: 188
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
45 and 76 are also numbers...what happens there?
 
pras
Ranch Hand
Posts: 188
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi Bert ,
i understood the logic in page 487

and probably i got the hint from jespers reply

ie whitespace is taken as delimiter so the value returned!!
 
The overall mission is to change the world. When you've done that, then you can read this tiny ad:
Clean our rivers and oceans from home
https://www.kickstarter.com/projects/paulwheaton/willow-feeders
reply
    Bookmark Topic Watch Topic
  • New Topic