• 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
  • Paul Clapham
  • Tim Cooke
  • Jeanne Boyarsky
  • Liutauras Vilda
Sheriffs:
  • Frank Carver
  • Henry Wong
  • Ron McLeod
Saloon Keepers:
  • Tim Moores
  • Frits Walraven
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Himai Minh

Scanner doubt

 
Ranch Hand
Posts: 125
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
import java.util.*;

class Emu {
static String s = "-";
public static void main(String[] args) {
Scanner sc = new Scanner("123 A 3b c,45, x5x,76 82 L");
while(sc.hasNextInt()) System.out.print(sc.nextInt() + " ");

}
}
can you explain me what would be the output of the following program
 
Ranch Hand
Posts: 558
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Sravanthi,

Scanner sc = new Scanner("123 A 3b c,45, x5x,76 82 L");
when you don't supply the splitter string then, it will take space as default splitter.

hasNextInt() -- true
nextInt() -123 (moves the pointer to next token "A")

hasNextInt() -- false comes out of loop;
-----------------------------------------------------

If you want to print all integers in that string, write like this

import java.util.*;

class Emu {
static String s = "-";
public static void main(String[] args) {
Scanner sc = new Scanner("123 A 3b c,45, x5x,76 82 L");

while(sc.hasNext()) // use this to reach all tokens
if(sc.hasNextInt()){
System.out.print(sc.nextInt() + " ");
}
else{
sc.next(); // you need to move control to next token
}
}
}

Got me?
 
sravanthi pulukuri
Ranch Hand
Posts: 125
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Problem is little tricky,little bit of common sense missed in me
Thanks
sorry for trouble
 
Live ordinary life in an extraordinary way. Details embedded in this tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic