Download Scanners

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Computer Science - I/O Notes
Input and output are so common that an abbreviation has been created: I/O (pronounced eye-oh). I/O operations
are very complicated, both at the software level and at the electronic level. Part of the problem is that the way in
which data is organized outside the computer is different from the way it is organized inside the computer. Lots
of computation is needed to convert data between its various forms. Luckily, most of the complication has been
hidden inside methods that your program can use.
These notes use methods of the class java.util.Scanner for doing input. Scanner is not part of the
fundamental Java language, but is part of a package, java.util, that you can include in your program.
Think of a package as a tool box and the classes within it as tools. Different programs need different tools and
include different packages.
It may seem odd to you that Java itself does not have I/O built into it. The reason for this is that there are very
many types of I/O, and a language that has all of them built in would be large and cumbersome. A language
used for professional software development such as Java (or C or C++ or any of several others) allows the
programmer to pick the right I/O package for the job.
In general, a program may have several input streams flowing into it and several output streams flowing out of
it. For most of the programs in these notes, there are three I/O streams:
System.in — the input stream.
System.out — the output stream for normal results.
System.err — the output stream for error messages.
Normally System.in is connected to the keyboard and the data are characters. System.out and
System.err both are connected to the monitor, and also are character data. These notes do not use
System.err.
When a Scanner object is constructed with System.in , it scans the standard input stream of characters for
patterns that the program asks for and (sometimes) converts those characters to a specific data type. For
example, the nextInt() method is used to match characters that can be converted to an int.
The hasNextInt() method returns true if the next set of characters in the input stream can be read in as an
int. If they can't be read as an int, or if the end of the file has been reached, then it returns false.
There are several hasNext methods that are usually used along with their corresponding next methods.
The table shows several:
Methods of Scanner
Usually your programs will use the methods for int and
double, and the hasNext() and next() methods.
These last two methods work with tokens which are groups of
any characters delimited (surrounded) by one or more spaces.
Here is a Java program. It reads characters from the keyboard
and creates a String object to contain them. A reference to
the object is put in inData. Then it sends the characters from
that String to the monitor.
HasNext
Method
Reading Method
hasNext()
next()
hasNextDouble()
nextDouble()
hasNextFloat()
nextFloat()
hasNextInt()
nextInt()
hasNextLine()
nextLine()
hasNextLong()
nextLong()
import java.util.Scanner;
class Echo
{
public static void main (String[] args)
{
String inData;
Scanner scan = new Scanner( System.in );
System.out.println("Enter the data:");
inData = scan.nextLine();
System.out.println("You entered:" + inData );
}
}
The line import java.util.Scanner; says to use the Scanner class from the
package java.util. The java.io package is imported automatically when you import Scanner.
class Echo
The program defines a class named Echo that contains a single method, its main() method.
public static void main ( String[] args )
All main() methods start this way. Every program should have a main() method.
String inData;
The program creates a String object referred to by the reference variable inData.
Scanner scan = new Scanner( System.in );
This creates a Scanner object, referred to by the reference variable scan.
System.out.println("Enter the data:");
This calls the method println to print the characters "Enter the data:" to the monitor.
inData = scan.nextLine();
This uses the nextLine() method of the object referred to by scan to read a line of characters from the
keyboard. A String object (referred to by inData) is created to contain the characters.
System.out.println("You entered:" + inData );
This first creates a String by concatenating "You entered:" to characters from inData, then
calls println() to print that String to the monitor.
nextInt()
The nextInt() method of a Scanner object reads in a string of digits (characters) and converts them into
an int type. The Scanner object reads the characters one by one until it has collected those that are used for
one integer.
The nextInt() method scans through the input stream character by character, gathering characters into
groups that can be converted into numeric data. It ignores any spaces and end-of-lines that may separate these
groups.
Here is a statement from a program:
num = scan.nextInt()
RECALL: Assignment statements work in two steps:
1. Evaluate the expression on the right of the equal sign,
2. Put the value in the variable on the left.
In this particular assignment statement, the expression on the right scans a group of characters from the input
stream and converts them into an int, if that is possible. Then the numeric result is stored into num.
If the group of characters cannot be converted, Java throws an Exception and stops your program.
An Exception object contains information about what went wrong in a program. Industrial-strength
programs may examine the exception and try to fix the problem. Our programs (for now) will just stop.
Here is another example. It asks the user for two integers which are then added together and the sum written
out.
import java.util.Scanner;
class AddTwo
{
public static void main (String[] args)
{
Scanner scan = new Scanner( System.in );
int first, second, sum ;
// declaration of int variables
System.out.println("Enter first integer:");
first = scan.nextInt();
// read chars and convert to int
System.out.println("Enter second integer:");
second = scan.nextInt();
// read chars and convert to int
sum = first + second;
// add the two ints, put result in sum
System.out.println("The sum of " + first + " plus " + second +" is " + sum );
}
}
Here is a sample run:
Enter first integer:
12
Enter second integer:
-8
The sum of 12 plus -8 is 4
Integer Division Tester
Here is a new program made by modifying the first program.
The user enters two integers, dividend and divisor.
The program calculates and prints the quotient and the remainder.
The program calculates and prints quotient * divisor + remainder.
import java.util.Scanner;
class IntDivideTest
{
public static void main (String[] args)
{
Scanner scan = new Scanner( System.in );
int dividend, divisor ;
int quotient, remainder ;
// int versions of input
// results of "/" and "%"
System.out.println("Enter the dividend:");
dividend = scan.nextInt();
// read the dividend
System.out.println("Enter the divisor:");
divisor = scan.nextInt();
// read the divisor
quotient = dividend / divisor ;
remainder= dividend % divisor ;
// perform int math
System.out.println( dividend
System.out.println( dividend
System.out.println( quotient
" + " + remainder + " is
}
}
+
+
+
"
"
"
"
+
/ " + divisor + " is " + quotient );
% " + divisor + " is " + remainder );
* " + divisor +
(quotient*divisor+remainder) );