|
Character Input and Output in Java
An Introduction |
|
Prof. David Bernstein |
| Computer Science Department |
| bernstdh@jmu.edu |
String objectsScanner
Scanner (cont.)int is the
only thing on a line), you will need to
invoke nextLine() immediately after
invoking one of these methodsBufferedReader
BufferedReader from an
InputStreamReader or FileReader
readLine() method (which
throws IOException)String object into parts (i.e., tokenize)split():
StringTokenizer:
nextToken()
nextToken() throws
NoSuchElementException which can be used to handle
situations with too few fieldsScanner (cont.)import java.util.Scanner;
/**
* An example that illustrates the use of the Scanner class
*
* @author Prof. David Bernstein, James Madison University
* @version 1.0
*/
public class ScannerExample
{
/**
* The entry point of the application
*
* @param args The command-line arguments
*/
public static void main(String[] args)
{
int age, weight;
double salary;
Scanner keyboard;
String line, name;
String[] parts;
keyboard = new Scanner(System.in);
System.out.print("Name: ");
name = keyboard.nextLine();
System.out.print("Salary: ");
salary = keyboard.nextDouble();
keyboard.nextLine(); // Consume the end-of-line character
System.out.print("Phone number (###-###-####): ");
line = keyboard.nextLine();
System.out.print("Age Weight (# #): ");
age = keyboard.nextInt();
weight = keyboard.nextInt();
keyboard.close();
}
}
BufferedReader (cont.)import java.io.*;
import java.util.*;
/**
* An example that illustrates the use of the Scanner class
*
* @author Prof. David Bernstein, James Madison University
* @version 1.0
*/
public class BufferedReaderExample
{
/**
* The entry point of the application
*
* @param args The command-line arguments
* @throws IOException if any line can't be read
*/
public static void main(String[] args) throws IOException
{
BufferedReader in;
double salary;
InputStreamReader isr;
int age, weight;
String line, name, phone;
String[] tokens;
StringTokenizer st;
isr = new InputStreamReader(System.in);
in = new BufferedReader(isr);
System.out.print("Name: ");
name = in.readLine();
System.out.print("Salary: ");
line = in.readLine();
salary = Double.parseDouble(line);
System.out.print("Phone number (###-###-####): ");
phone = in.readLine();
System.out.print("Age Weight (# #): ");
line = in.readLine();
// One way to tokenize: Using the split() method
tokens = line.split(" ");
age = Integer.parseInt(tokens[0]);
weight = Integer.parseInt(tokens[1]);
// Another way to tokenize: Using a StringTokenizer
st = new StringTokenizer(line, " ");
age = Integer.parseInt(st.nextToken());
weight = Integer.parseInt(st.nextToken());
in.close();
}
}
PrintWriter
PrintWriter (cont.)
: Other Ways to Format Outputimport java.io.*;
import java.text.*;
/**
* An example that illustrates the use of the NumberFormat
* class
*/
public class ChoiceFormatExample
{
/**
* The entry point of the application
*
* @param args The command-line arguments
*/
public static void main(String[] args) throws IOException
{
ChoiceFormat formatter;
double grade;
// The intervals are half-open [low, high)
double[] limits = { 0, 60, 70, 80, 90};
String[] letterGrades = {"F","D","C","B","A"};
String outputString;
// Note that the constuctor is used (unlike NumberFormat)
formatter = new ChoiceFormat(limits, letterGrades);
grade = 82.5;
outputString = formatter.format(grade);
System.out.println("Numeric Grade: "+grade);
System.out.println("Letter Grade: "+outputString);
}
}
: Internationalizing/Localizing Output
: Internationalizing/Localizing Output (cont.)
import java.io.*;
import java.text.*;
import java.util.Locale;
/**
* An example that illustrates the use of the NumberFormat
* class
*/
public class NumberFormatExample
{
/**
* The entry point of the application
*
* @param args The command-line arguments
*/
public static void main(String[] args) throws IOException
{
NumberFormat formatter;
String outputString;
// Note that the constuctor is often not used directly
formatter = NumberFormat.getInstance();
// An example similar to %d in printf
formatter.setMinimumIntegerDigits(5);
formatter.setGroupingUsed(false);
outputString = formatter.format(20);
System.out.println(outputString);
// An example similar to %f in printf
formatter.setMinimumIntegerDigits(0);
formatter.setMaximumFractionDigits(2);
formatter.setGroupingUsed(false);
outputString = formatter.format(1052.2891554);
System.out.println(outputString);
// An example that prints currency values
formatter = NumberFormat.getCurrencyInstance();
outputString = formatter.format(1953249.25);
System.out.println(outputString);
// An example that prints currency values in a different locale
formatter = NumberFormat.getCurrencyInstance(Locale.GERMANY);
outputString = formatter.format(1953249.25);
System.out.println(outputString);
}
}
File
classFile Objects:
java.io.IOException (they
actually throw a more "specific" exception -- we'll learn
what this means later)
BufferedReader
import java.io.*;
import java.util.*;
/**
* An example that illustrates the use of reading from a file
* and using the StringTokenizer class.
*
* @author Prof. David Bernstein, James Madison University
* @version 1.0
*/
public class FacultyRecordTokenizer
{
/**
* The entry point of the application
*
* @param args The command-line arguments
*/
public static void main(String[] args)
{
BufferedReader in;
FileReader fileReader;
InputStreamReader isReader;
String delimiters, email, line, name, phone;
StringTokenizer tokenizer;
try
{
// Setup the reader and writer
fileReader = new FileReader("cs.txt");
in = new BufferedReader(fileReader);
// Keep reading, tokenizing and processing
while ((line = in.readLine()) != null)
{
tokenizer = new StringTokenizer(line, "\t", false);
while (tokenizer.hasMoreTokens())
{
try
{
name = tokenizer.nextToken();
phone = tokenizer.nextToken();
email = tokenizer.nextToken();
// Do something with the information
}
catch (NoSuchElementException nsee)
{
// Do something when there is a problem
}
}
}
in.close();
}
catch (IOException ioe)
{
System.err.println("IO Problem");
}
}
}
Scanner
import java.io.*;
import java.util.*;
/**
* An example that illustrates the use of reading from a file
* and using the Scanner class.
*
* @author Prof. David Bernstein, James Madison University
* @version 1.0
*/
public class FacultyRecordScanner
{
/**
* The entry point of the application
*
* @param args The command-line arguments
*/
public static void main(String[] args)
{
Scanner in;
String delimiters, email, line, name, phone;
try
{
// Setup the reader and writer
in = new Scanner(new File("cs.txt"));
in.useDelimiter("\t");
// Keep reading and processing until EOF
while (in.hasNext())
{
name = in.next();
phone = in.next();
email = in.nextLine(); // Also consume the end-of-line character
email = email.substring(1); // Strip-off the leading delimiter
// Do something with the information
}
in.close();
}
catch (IOException ioeFile)
{
System.err.println("Unable to open the file.");
}
}
}
import java.io.*;
import java.util.*;
/**
* An application that asks the user simple addition questions.
*
* This application demonstrates the use of console I/O and file
* output.
*
* @author Prof. David Bernstein, James Madison University
* @version 1.0
*/
public class Quizzer
{
private static final int NUMBER_OF_QUESTIONS = 10;
/**
* The entry point of the application.
*
* @param args The command-line arguments (which are ignored)
*/
public static void main(String[] args)
{
boolean status;
BufferedReader keyboard;
int actual, correct, expected, left, right;
PrintWriter log;
Random rng;
String line;
correct = 0;
rng = new Random();
keyboard = new BufferedReader(new InputStreamReader(System.in));
// Ask the questions and check the answers
for (int i=0; i<NUMBER_OF_QUESTIONS; i++)
{
left = rng.nextInt(10);
right = rng.nextInt(10);
expected = left + right;
System.out.printf("%d. What is %d + %d? ", i+1, left, right);
try
{
line = keyboard.readLine();
try
{
actual = Integer.parseInt(line);
status = (actual == expected);
}
catch (NumberFormatException nfe)
{
status = false;
}
}
catch (IOException ioe)
{
status = false;
}
if (status)
{
++correct;
System.out.printf("Correct!\n");
}
else
{
System.out.printf("Sorry, that's not correct.\n");
}
}
// Create a log file that contains a summary of the results
try
{
log = new PrintWriter(new File("results.txt"));
log.printf("Correct: %2d\n", correct);
log.printf("Incorrect: %2d\n", NUMBER_OF_QUESTIONS - correct);
log.close();
}
catch (FileNotFoundException fnfe)
{
System.out.printf("Unable to create the log file.");
}
}
}