0% found this document useful (0 votes)
14 views

Slide Set Three - Basic Data Input and Output Using Scanner

This document discusses using the Scanner class in Java to get input from the user via the keyboard. It explains how to create a Scanner object, use various methods like nextLine(), nextInt() and nextDouble() to read string, integer and double values, and potential issues that may arise from the order of method calls.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Slide Set Three - Basic Data Input and Output Using Scanner

This document discusses using the Scanner class in Java to get input from the user via the keyboard. It explains how to create a Scanner object, use various methods like nextLine(), nextInt() and nextDouble() to read string, integer and double values, and potential issues that may arise from the order of method calls.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 16

Software and Information Systems Testing

INFO6066

Using the Scanner class to get input from the user

INFO6066
Software and Information Systems Testing

Recap: Anatomy of a Java Program


• /*class documentation header contains program name, purpose,
• * who wrote it, and date written
*/
public class HelloWorld //class name
{ //opening class curly brace
public static void main(String[ ]args) //main method declaration
{
System.out.print(“Hello world, it’s me!”);

Call to print() method Argument passed to print method


} //end main //closing brace for main method
} //end class //closing brace for class

INFO6066
Software and Information Systems Testing

Console Input Using the Scanner class.


• Q. How can we get a program to accept input from the keyboard?
• Any data that is typed into the keyboard is stored in a special area of
memory called the keyboard buffer (T!)
• To get this data, our program has to read the data from the
keyboard buffer and return it to our program.
• Java does have a System.in() method, but it is limited to reading
only one character at a time from the keyboard buffer.
• We need something that can read a whole string of characters or
digits from the user.

INFO6066
Software and Information Systems Testing

Console input, continued…


• The Java API (Application Programmer Interface) has thousands of useful
classes that are stored in several hundred “packages” or class libraries that
we can access.(T!)

• To access any package we can add an ‘import’ statement to our program.


This tells the Java Virtual Machine where to go in the library to find the
code that it needs to run our program. (T!)

• Think of the import statement as your library card which allows you to
access any class in the Java library.

INFO6066
Software and Information Systems Testing

Accessing the Scanner Class


• The java.util package (“util” stands for utility) contains a class called
Scanner, which takes the System.in object as an argument or parameter,
and then modifies it so that it can read more than one character at a time.
• It has several methods for reading the keyboard buffer, such as nextInt()
for int, nextDouble() for doubles, and nextLine() for getting String input.
• To access it, you need to put this line of code above your class declaration
statement (your public class ClassName line)

import java.util.Scanner; //note that Scanner has a capital ‘S’

• This also will work: import java.util.*; //* is a wildcard character

INFO6066
Software and Information Systems Testing

Creating a Scanner object

• To use it, you first have to ask Java to create a Scanner object in your program.
• We have to give this object a name or “reference”, and we often use the variable
name “input” to name the Scanner object (although you can name it anything you
want, “input” is a nice short name to type, as opposed to “keyboardReader”).

Scanner input = new Scanner(System.in);

• Now that you have created the Scanner object, you “reference it” (refer to it) by using
its name…input System.in is the “argument” we pass to the
“constructor method”of the Scanner class.

INFO6066
Software and Information Systems Testing

Using a Scanner object to get an String value from the keyboard


• There are two methods for reading in text from the keyboard:
next(), and nextLine().
• next() stops reading when it sees either a space or the End-Of-Line character. It will
only read in single words with no spaces.
• nextLine() will read spaces, so you can enter multiple words.
• //Example use of nextLine() to read first and last names
System.out.print(“Enter your full name…”);

//call nextLine() method to read the keyboard buffer


String userName = input.nextLine( );

//print out the result


System.out.println(“Your name is…” + userName);

INFO6066
Software and Information Systems Testing

Warning! nextLine() vs next() method


• The nextLine() method will read AND RETURN every character that is typed into the keyboard
buffer, including spaces and the EOL (End-of-line) character that is caused by pressing the
ENTER or RETURN key.
• NOTE: the EOL character is also referred to as the ‘New Line’ character, or the ‘carriage return’
(cr)character.
• Thus, when the nextLine() method reads the keyboard buffer, it cleans out and returns every
character that it finds. In other words, it “flushes” the buffer clean. (Like a polite house guest
who uses your washroom)(T!)
• The next() method does not do quite as much. It will start reading characters from the buffer,
but it stops as soon as it sees a space character, or the EOL character.
IMPORTANT: the next() method DOES NOT FLUSH the buffer clean. It leaves the space or the
EOL character in the buffer (this house guest is rude, and doesn’t flush).
• This can cause problems if you want to read in several inputs from the user and you follow
the use of the next()method with a nextLine() method call.

INFO6066
Software and Information Systems Testing

The problem of nextLine() following a next() call


• If the nextLine() method is called, it immediately checks the keyboard buffer to see
if anything is there.
• If it sees an EOL or space character in the buffer that was left behind by a previous
call to next(), it grabs it and returns it right away, and says to itself “My work is
done here…”.
• If the nextLine() method sees an empty buffer, it waits until something is put into
the buffer that ends with the EOL character (when user presses the ENTER key),
and then it collects all of the characters and returns them to whatever line of code
called the method.
• Work – around SOLUTION: if you use a next() call to read in some data, and plan to
read in more data afterwards using nextLine(), do a BUFFER FLUSH by just calling
the nextLine() method without assigning its return value to anything, i.e.
input.nextLine();
• This will “flush” out any space or EOL character left in the buffer by the (rude house
guest ) next() method.

INFO6066
Software and Information Systems Testing

Using a Scanner object to get an integer value from the keyboard


• Example code showing how to use a Scanner object to read an int value from
the keyboard buffer:

Scanner input = new Scanner(System.in);


• //prompt the user to enter a value
System.out.print(“Enter an integer value…”);

//call nextInt() method to read the keyboard buffer. It will return any digit
characters that it finds in the buffer BUT NOT THE EOL!
int userInput = input.nextInt( );

//print out the result


System.out.println(“You entered a…” + userInput);

INFO6066
Software and Information Systems Testing

Using a Scanner object to get a double value from the keyboard


• Example code showing how to use a Scanner object to read a double value
from the keyboard buffer:

Scanner input = new Scanner(System.in);


• //prompt the user to enter a value
System.out.print(“Enter a double value…”);

//call nextDouble() method to read the keyboard buffer. It will return any
digits or a decimal point, BUT NOT THE EOL!
double userInput = input.nextDouble( );

//print out the result


System.out.println(“You entered the value…” + userInput);

INFO6066
Software and Information Systems Testing

Warning! Using nextLine() after using a numeric


read method such as nextInt()

• Trying to read in text output using nextLine() after reading in numeric output using
nextInt() or nextDouble() or any of the other methods for reading in numeric input
can cause an annoying logic error if you are not careful.
• Remember that the nextLine() method will “flush” the keyboard buffer and
completely empty it of all characters, including the EOL or new line character (the
ENTER key).
• The methods for reading numeric input are also “rude house guests” as they only
read in numeric characters, or the period character if a decimal point is used.
• When the numeric reading methods encounter the EOL character, they stop
reading, but they also leave the EOL character behind in the buffer! The buffer is
not “flushed” clean.

INFO6066
Software and Information Systems Testing

Warning, cont’d…
• All of the numeric reading methods are rude house guests (just like the next()
method), who do not “flush” after using your bathroom.
• This EOL character that is left in the buffer by the numeric reading methods will
cause problems if you then attempt to use nextLine() to read some text input from
the user.
• Again, the nextLine() method is triggered by the presence of any characters in the
keyboard buffer. If there is an EOL character left in there from a previous read of
numeric input, then nextLine() will immediately run, before the user has a chance
to input any text data that you might be asking for.
• Again, you need to “flush” the buffer after you read in any numeric input, if you
need to use nextLine() after the numeric read .
• To do a buffer flush, you just enter this line: input.nextLine();
• There is a YouTube video on this topic by Professor Graham Mansfield , at
http://www.youtube.com/watch?v=bnNHKnHMbt4

INFO6066
Software and Information Systems Testing

Recap: Creating a Scanner Object


• Step 1: place an import statement above your class declaration
header so the JDK knows to go to the java.util package to get the
necessary code:
import java.util.Scanner; //note…capital ‘S’ on Scanner!
public class TestScanner

• Step 2: create a Scanner object using this line of code:


Scanner input = new Scanner(System.in);
Scanner’s constructor method takes a System.in object as an argument

• Step 3: create a variable that will hold the value that the Scanner
method will return from the keyboard buffer.

INFO6066
Software and Information Systems Testing

Recap…when do I flush?

• If you use the next() method, or do a numeric read method such as nextInt() or
nextDouble(), remember that they leave the EOL character behind in the buffer.
• If you then ask the user to enter some text that you plan to read using nextLine()
(i.e. their full name, with spaces), the presence of the EOL character will cause the
nextLine() method to fire right away, before the user has a chance to type in
anything.

• Before you prompt the user to enter the text, do a “buffer flush” by using this line:
input.nextLine(); //flushes the buffer clean
• Once the buffer is flushed, you can ask the user to enter their text.

INFO6066
Software and Information Systems Testing

Homework
• Read the rest of Chapter Two:
• Please engage with the exercises.
• Answer the questions.
• Complete the coding examples.

INFO6066

You might also like