About scanner, see a nice tutorial.
Original website: https://www.cs.utexas.edu/users/ndale/Scanner.html
Scanner class
The Scanner class is a class in Java.util, which allows the user to read values of various types. There is far more methods in class Scanner than you'll need in this course. We only cover a small useful subset, ones this allow us to read in numeric values from either the keyboard or file without Have to convert them from strings and determine if there is more values to is read.
Class Constructors
There is constructors that is particularly Useful:one takes an InputStream object as a parameter and the other take S a FileReader object as a parameter.
Scanner in = new Scanner (system.in); System.in is an inputstreamscanner inFile = new Scanner (New FileReader ("MyFile"));
If The file≥myfile≤is isn't found, a filenotfoundexception is thrown. This was a checked exception, so it must was caught or forwarded by putting the Phrase≥throws filenotfoundexception≤on the Header of the method in which the instantiation occurs and the header of any method that calls the method in which the Stantiation occurs.
Numeric and String Methods
Method |
Returns |
int Nextint () |
Returns the next token as an int. If the next token is not a integer, Inputmismatchexception is thrown. |
Long Nextlong () |
Returns the next token as a long. If the next token is not a integer, Inputmismatchexception is thrown. |
Float Nextfloat () |
Returns the next token as a float. If the next token is not a float or was out of range, Inputmismatchexception is thrown. |
Double nextdouble () |
Returns the next token as a long. If the next token is not a float or was out of range, Inputmismatchexception is thrown. |
String Next () |
Finds and returns the next complete token from this scanner and returns it as a string; A token is usually ended by whitespace such as a blank or line break. If not token exists, Nosuchelementexception is thrown. |
String nextline () |
The rest of the Returns, excluding any line separator at the end. |
void Close () |
Closes the scanner. |
The Scanner looks for tokens in the input. A token is a series of characters this ends with the what Java calls whitespace. A whitespace character can be a blank, a tab character, a carriage return, or the end of the file. Thus, if we read a line, there is a series of numbers separated by blanks, the scanner would take each number as a separate Token. Although we had only shown four numeric methods, each numeric data type had a corresponding method that reads values of T Hat type.
The numeric values may all is on one line with blanks between each value or may is on separate lines. whitespace characters (blanks or carriage returns) Act as separators. The next method returns the next input value as a string, regardless of what are keyed. For example, given the following code segment and data
int number = in.nextint (); float real = in.nextfloat (); long number2 = in.nextlong (); double Real2 == In.next ();
44 23
2222222222
22222.33 End
Would is stored in number; 23.0 would is stored in real; 2222222222 would is stored in number2; 22222.33 would is stored in real2; And≥end≤would is stored in string. Notice This method nextfloat reads an integer and stores it as a float value. This is the legal because an integer value can be stored exactly as a real value; There is no ambiguity. If we had keyed a decimal point after the, the system would has thrown a inputmismatchexception (a checked exception) Regardless of whether or not a Non-zero value followed the decimal point. An arbitrary real number cannot is stored exactly as an integer; It is ambiguous. Remember that anything ambiguous is illegal.
Nextline reads the rest of the line and returns it as a string. The carriage return is consumed and is not a appended to the string. The numeric reads don't consume the whitespace, so if a nextline are issued at after a numeric read and the numeric value is at the end of the line, Nextline returns the empty string. Nextline never jumps over a carriage return to get the next line of input. For example, the following code fragment
int number == in.nextline (); float real ==
And the data shown above, string would contain≥23≤and string2 would contain the empty string.
Here's a program that uses these methods, followed by the output. Look through the application carefully to being sure you understand how the output is generated.
//**********************************************************************//Class Numericinput demonstrates reading numeric values.//**********************************************************************ImportJava.util.Scanner;Importjava.io.*;//Access System.out Public classnumericinput{ Public Static voidMain (string[] args) {//DeclarationsScanner in=NewScanner (system.in); intinteger; LongLongInteger; floatRealNumber; DoubleDoublereal; String string1; String string2; //PromptsSystem.out.println ("Enter An integer, a long Integer," + "a floating-point"); System.out.println ("Number, another floating-point number," + "and a string."); System.out.println ("Separate each with a blank or return."); //Read in Valuesinteger=In.nextint (); LongInteger=In.nextlong (); RealNumber=in.nextfloat (); Doublereal=in.nextdouble (); String1=In.nextline (); System.out.println ("Now enter another value."); string2=In.next (); System.out.println ("Here's what you entered:"); System.out.println (integer+ "+ LongInteger +" "+ RealNumber +" "+ Doublereal +" "+ string1 +" and "+string2); } }
Output:
long Integer, a floating-pointnumber, another floating-return. 232425.0 233333333333333.444 Hellonow Enter another value. 23.4 Here's what'sentered:25.0 2.3333333333333344E14 Hello and 23.4
Boolean Methods
We said that the Scanner methods that read numeric data throw a Inputmismatchexception exception if the next value isnπt W Hat the method expects. We can avoid that problem using Boolean methods. Here's four useful, Boolean methods, the Allow us to check for be sure, that next value is, what we expect.
M Ethod |
Returns |
boolean hasnextline () |
returns true if the scanner have another line in its input; falseotherwise. |
boolean hasnextint () |
returns true if the next token in the scanner can be interpreted as An int va Lue. |
boolean hasnextfloat () |
returns true if the next toke in the scanner can be interpreted as a float value. |
Let's write a code fragment that instantiates a scanner and reads and prints an integer value and a second integer value I F there is one.
New Scanner (system.in); System.out.println (In.nextint ()); if (In.hasnextint ())
There is methods equivalent to these for each of the Java built-in types.
The following application applies the appropriate reading method to the data which is keyed in.
//************************************************************************//Mixedtypeinput//This application demonstrates testing before reading//Sure to use the correct input method for the data.//************************************************************************ ImportJava.io.*;ImportJava.util.Scanner; Public classmixedtypeinput{ Public Static voidMain (string[] args) {DoubleNumber ; Scanner in=NewScanner (system.in); System.out.println ("Enter Your gross income:"); if(In.hasnextint ()) { number= (Double) In.nextint (); System.out.println ("You entered" +Number ); } Else if(In.hasnextfloat ()) { number= (Double) in.nextfloat (); System.out.println ("You entered" +Number ); } Else if(In.hasnextdouble ()) { number=in.nextdouble (); System.out.println ("You entered" +Number ); } ElseSystem.out.println ("Token not a integer or a real value."); }}
The application is run four times. The input is shown in red.
Enter your gross income:5500055000.0 Enter Your gross income:55000.055000.0 5.50000001024E11 Enter your gross income:fifty Five hundredtoken not an integer or a real value.
What would happen if there were no tokens in the the previous example? Each of the Boolean methods would return false. They return true if and only if the next token in the scanner can is interpreted as a value of their type. We return to the subject of reading data from files later on this chapter and show how to use these Scanner methods to all ow us to read multiple values from a line in a file. Except for some trivial cases, we must combine reading operations with loops to read through all of the data on a file.
Files
To read from a file rather than the keyboard, you instantiate a Scanner object with a FileReader object rather than System . In.
Scanner in = new Scanner (system.in); Reading from the keyboard
Scanner inFile = new Scanner (new FileReader (≥infile.dat≤)); Reading from a file
Although all of the methods applied to keyboard input can is applied to file input, there is methods that is usually app Lied only to files. These is the methods that ask of there is more values in the file. If There is no further values in a file, we say the file was at the end of the file (EOF). For example,
Infile.hasnext (); Infile.hasnextline ();
Return true if InFile have another token in the file or if there was another line in the file. What is the methods hasnextint and so forth, we used to look ahead at the type of the next input token? These can used to determine if there is more data values in the file, provided your know exactly how the files is Orga Nized
Be sure to close all files. If you forget to close system.in, no harm are done, but forgetting to close a file can cause problems.
Scanner Simple Introduction