Along with the version of Java 5 came a new set of classes, including one that allows us to read data from the keyboard even easier than previously seen classes.
Scanner class of java.util package which gives us the ability to process data entered from the keyboard under primitive type they belong to these entries. This is achieved by treating the input data as tokens of an expression separated by a boundary that we have specified.
Let's see an example of the above ...
turns out that we need to write a Java program that allows capturing personal data of a company's payroll. We read data such as name, address, age and salary of an employee. We know the names that will introduce the program String class, like directions. While the employee's age must be an integer value and the wage is given in numbers with decimals. In short:
String name = "";
String address = "";
int age = 0;
double salary = 0.0;
Earlier we saw that the class BufferedReader capture data allowed keyboard through method readLine () , which returns a value type we String would subsequently be converted to numeric processing. However, the class Scanner contains specific methods for reading data much faster and safer, but above all, without the need for conversions ourselves. Following is a summary of these methods:
constructor Summary:
Scanner (File file)
Creates a new Scanner that produces values \u200b\u200bfrom a specified file. Scanner (InputStream inputStream)
Creates a new Scanner that produces values \u200b\u200bfrom an input stream of data. Scanner (String source)
Creates a new scanner from a particular string. Summary of methods:
void close () Closes
Pattern Scanner delimiter () Returns
Scanner delimiter pattern
findInLine String (Pattern pattern)
Try searching a string in the scanner to ignore the patterns
boolean hasNext ()
Returns true if the value contains more tokens Scanner
boolean hasNext (String pattern )
Returns a true value if the Scanner contains the specified pattern
nextBoolean boolean ()
Scans the next token of the input to a Boolean value and returns that value.
nextByte byte ()
Scans the next token of the input as a byte.
double nextDouble ()
Scans the next token of the input as a double. Float
nextFloat ()
Scans the next token of the input as a float.
int nextInt ()
Scans the next token of the input as an int. String
nextLine () Returns
entire current line.
long nextLong ()
Scans the next token of the input as a long.
short nextShort ()
Scans the next token of the input as a short.
Then, with the Scanner class can perform data reads to solve our example.
0 comments:
Post a Comment