RU beehive logo ITEC Department logo
ITEC 120
2007spring
ibarland,
jpittges

homeinfoexamslectureslabshws
RecipeLawsliessyntaxjava.lang docsjava.util docs

lect12b
input: Scanner

Reading input is more complicated than just calling a read method. The reason is, if you read straight from the keyboard, you get raw characters: the input file (or the keyboard) contains “33   hi 44.4” followed by a return, then reading that file (or the keyboard) merely gives you a dozen characters or so. If you want to convert some to numbers, and if you want to skip over multiple spaces, then you need an expert who is good at reading that sequence of characters, and who can tokenize it -- turn it into a sequence of an int, a word, and a double.

Java provides such an input-reading specialist -- class java.util.Scanner.

import java.util.Scanner;

  
java.util.Scanner s;

// Make a new Scanner which takes its input from a particular String:
s = new java.util.Scanner( "4 score and 7 years");

s.nextInt()    // returns 4
s.next()       // returns "score"  
s.next()       // returns "and"  
s.nextInt()    // returns 7  
s.hasNextInt() // returns false  
s.hasNext()    // returns true  
s.next()       // returns "years"  
s.hasNext()    // returns false  

You can make new Scanners which scan input from other sources, besides a particular String. Construct each of the following Scanners, and read from it!:


1 Full name: java.lang.System.in. Since java always re-writes your programs to start with “import java.lang.*”, we can use its abbreviated name.
By the way, you should be able to discern the following questions: is in a method or field? Is it static? Is it public, or is it private?      

2 In this case, if you try it out, you realize that web pages are written in html; in html the notion of the “next word” is different from where the next whitespace occurs. Indeed, people have written specialized classes which extend Scanner to so that the next method returns the next word in a way that is appropriate for html.      

homeinfoexamslectureslabshws
RecipeLawsliessyntaxjava.lang docsjava.util docs


©2007, Ian Barland, Radford University
Last modified 2007.Aug.27 (Mon)
Please mail any suggestions
(incl. typos, broken links)
to iba�rlandrad�ford.edu
Powered by PLT Scheme