Showing posts with label Scanner. Show all posts
Showing posts with label Scanner. Show all posts

Monday, February 25, 2013

Getting input

DOWNLOAD THE CODE: InputFromScannerPkg

The Scanner class
A class is a template for an object. A class contains methods for performing particular tasks. From one class we can create many object instances.

The Scanner class belongs to the Java library of classes. It contains methods for reading many different types of data, from different types of input.

System.out
You have already seen System.out in action when we print to the console. This is the default stream for output.

This statement causes the words “Print this’ to be printed to the console in Eclipse.

System.out.println(“Print this”);

What you cannot see, however, are the special line ending characters which this method places at the end of the line. When subsequent lines are printed using println(), they each begin on a new line.

Here’s a different way to print to the console:

System.out.print(“Print this”);

Notice that we are now using the print() method. This method does not include special line ending characters. Each subsequent line of characters that is printed using print() will begin immediately where the last line of characters left off.




and the output...


System.in
The following code example uses Scanner’s nextInt() method to read an int input from System.in (default input from console). The input is assigned to the int variable called aNumber.

Scanner myScanner = new Scanner(System.in);
int aNumber = myScanner.nextInt();


Scanner can be told to read different types of data - or tokens. By default, Scanner uses whitespace characters as delimiters of tokens (the characters that separate tokens).

In the case of the nextInt() function, Scanner is using whitespace to delimit tokens, and return the token as an int. (seen in the figure below).

Other Scanner functions of note include:

next() - Return the next token, of any type.
next(String pattern) - the next token is delimited by the pattern supplied as a parameter.
nextLine() - reads the current line and returns it.



and the output...

In the figures above, the user is prompted to enter information. Methods of the scanner class are used to read the input typed into the console, and assign it to variables. The variable values are then printed to the console.

You can read the entire Scanner class specification here:
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

Java I/O and Import statements
When we wish to use Scanner:
At the top of the code file we import a reference to the Scanner class by using the line:

import java.util.Scanner;

This line says that we intend to use the class called Scanner from the package called java.util.

In Java, all input and output (I/O) is performed by importing methods from the java.io or java.util packages.

Any source of input or destination of output is called a stream: keyboard, screen, network connection, a file, etc., are all streams.

There are three predefined Streams already open and ready to use in every program:
  •     System.in
  •     System.out
  •     System.err



Object Instantiation
To use the Scanner class, we must first declare an instance of Scanner and give it a name. Similar to declaring a variable in that we declare a type and an identifier. In this case, the type is Scanner.

As well as being declared, an object also needs to be instantiated. The use of the new keyword, instantiates the object called myScanner from the Scanner class.

Scanner myScanner = new Scanner(System.in);

In the next statement, we declare an int variable and assign it the value of the next int that is returned myScanner’s nextInt() function.


int aNumber = myScanner.nextInt();

You will notice that when we instantiated a Scanner object, we have also included System.in, inside of the parenthesis (round brackets). This is an example of passing data to a method. Often, a method needs data passed to it so that it can perform its task.

System.in is the input stream from the keyboard, via the Java console, so, we are telling the Scanner object to use this as its source.

Monday, June 11, 2012

File class

The Scanner & PrintWriter classes can read from & write to text files, respectively.

Each of these classes contains a constructor that accepts a File object.

The File class belongs to the java.io library (io stands for Input Output).

The example below declares a File object that references the io library directly. Notice that a String containing a filepath/filename is passed to the file's constructor. This File object called file, is then passed to the constructor of the Scanner object. In essence we are saying, read from this file at this location.


The next example declares a File object using a shorter declaration. The library reference has been done via an imports statement at the top of the code (not shown). Once again a String filepath/filename has been passed to the constructor. The file object is then passed to the constructor of the PrintWriter object. In short, we are saying, write (print) to this file at this location.


"File (Java)" ( http://bit.ly/JWg0sp )

"java.io (Java Platform SE 6)" ( http://bit.ly/JWhUcw )

String trim()

DOWNLOAD THE CODE: TrimmingWhitespace

The Java Character class defines whitespace as one of a few different types of characters, including the space character & a carriage return character.

The String class contains a trim() function which removes leading & trailing (at the beginning and at the end) whitespace.

For example, if we are reading a text file using Scanner, with a semi-colon as the delimiter, we only want to read the meaningful part of the string. Carriage returns should be discarded.

For our examples, we will use the following text file nums.txt. See screenshot below:



The code example below reads nums.txt, inside of a while loop.The semi-colon is used as the Scanner's delimiter. Each token in the string ends with a semi-colon and the next begins immediately after the semi-colon. This means that any carriage return characters may be included in the token. This is not ideal and will produce the following result:


Here is the output:


Note that the carriage return separating the lines between the tokens "five" and "six" has been read and rendered.

Using trim()
In the example below, we will trim() each token so that any whitespace such as carriage return characters are discarded.


Here is the output:




Monday, May 28, 2012

PrintWriter


DOWNLOAD THE CODE: PrintToFile.java

The PrintWriter class contains 2 very useful methods:
  • print(String)
  • println(String)
These methods write a String to a file.
The println method adds the end-of-line character after the string.

The constructor of the PrintWriter class accepts a file to write to. As such, a File object has been declared. The constructor of the File object accepts a String file path of the file's location. It is interesting to note that if the file has not already been created, the PrintWriter will create it automatically.

The example below contains 2 loops. The first loop writes the numbers 1-10 (using the loop counter) to data.txt using the print() method. As such, each number is written immediately after the last. The second loop also writes the numbers 1-10 to data.txt but uses the println() method so that each number is written on a new line.


Here is the output:




Throws FileNotFoundException. If you do not implement exception handling for this exception, the compiler will force you to rethrow it.

And if you want to read text file from a file, here's a post about the Scanner class.

"PrintWriter (Java Platform SE 7 )" ( http://bit.ly/LsOVki )

Here's a cat:


Wednesday, May 23, 2012

The split function

DOWNLOAD THE CODE: usingSplit.java.zip

The String class contains a split() function. This means that any single string may be split into several substrings, based upon a nominated delimiter character. split() returns an array of String, containing each substring.

Example 1: split a string using a space as the delimiter:

Output:



Example 2: split a string using a comma (,) as the delimiter:

Output:





Monday, May 21, 2012

Scanner class - Part 2.

DOWNLOAD THE CODE: Scanner.zip

<< Continued from part 1

In the next example, we will nominate a character to use as a delineation token - the semi-colon (;).

Below is the text file shoppinglist2.txt. Note that each line contains a semi-colon. Now, rather than defaulting to whitespace as the delineation token, the Scanner will look for the semi-colon character.


Here's the code:



Note that the Scanner's property useDelimiter has been set to use the semi-colon (;). Each token is now measured by the presence of a semi-colon.

Here's the result:







Sunday, March 18, 2012

Scanner class - Part 1

DOWNLOAD THE CODE: Scanner.zip

The Scanner class has methods for reading a number of different types of data such as String, int, Double & Boolean.

By default, the Scanner class uses whitespace to delineate tokens (lines, words, phrases, values, etc).

We can use the Scanner class to read input from keyboard input or from txt files.

Use Scanner to read keyboard input
The example below uses the Scanner class to read keyboard input. Scanner contains several methods for reading different types of data. In this example, the next() & nextInt() methods are used to read the input String and the input int, respectively.


The output:




Using Scanner to read from a text file
The following shoppinglist.txt file contains a number of shopping items. Each item is followed by a number representing the quantity required.


Declare an instance of File and then declare an instance of the Scanner class. Pass the file instance to the scanner instance.

The Scanner class contains a number of Boolean functions to determine whether there is another token of a specified type. The example below uses a while loop in conjunction with the Scanner's hasNext() method of Scanner to determine if another token of any type exists.  In effect, the loop has been primed to 'continue looping while there are more tokens to read'. When there are no more toekn to read, the loop will stop.




The output: 



The final token in this example is the character 1.

By default, the Scanner's next() method is using the whitespace separating the characters in the file, to delineate is string. As such, any string separated by whitespace, is being read in each pass of the loop. The statement input.next() reads the next token in the file.

Let's change the code a little to get these values onto the same line.

The while loop body now looks like this:


The first call to next() reads in the name of the shopping item and is printed to screen via the print() method. The second call to next() is used to read in the quantity is appended to the next line via the println() method. 

The output now looks like this:


Read on to learn about using a nominated deliminator character with the Scanner class.



"Scanner (Java Platform SE 7 )" ( http://bit.ly/ABSuGl )


Simple tutorial using the Scanner class: "Java For Complete Beginners - user input" ( http://bit.ly/Lkr7uN )

"Scanning (The Java™ Tutorials > Essential Classes > Basic I/O)" ( http://bit.ly/LkD03X )

"File (Java Platform SE 7 )" ( http://bit.ly/Jxdc9T )

"The while and do-while Statements (The Java™ Tutorials > Learning the Java Language > Language Basics)" ( http://bit.ly/LkGjIm )

Finding a char in a String. Example

Finds the Char at position 0 of the string


Getting input: The Scanner class

"Scanner (Java Platform SE 7 )" ( http://bit.ly/ABSuGl )