• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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!!
 
Well behaved women rarely make history - Eleanor Roosevelt. tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic