Java Input / Output

Getting Input from Java Input Dialogs
In our previous codes we have been dealing with values thatare is fixed in the source code. Inoeder to use a different radius, then you have to modify the source code and recompile it. This is not a convenient method. You can use the showInputDialog method in the JOptionPane class to get input at runtime. When this method is executed, a dialog is displayed to enable you to enter an input value, which is a string. After entering a string, click the OK button for the progam to accept the input and unload the dialog box. The input is returned from the method as a string. Example The first argument in the statement can always be null. Then the second argument is a string that prompts the user, this is a message diaplayed to the user and it guides the user on the type of input required. The third argument is the title of the input box (the message displayed in the title bar of the input box). The fourth argument can be JOptionPane.QUESTION_MESSAGE, which causes the icon to be displayed in the input box.

Example 1: String strEntered = JOptionPane.showInputDialog(null, str, title, JOptionPane.QUESTION_MESSAGE)); where str is a string for the prompting message, and title is a string for the title of the input dialog box. Example 2: JOptionPane.showInputDialog(str); where str is a string for the prompting message.

Converting Strings to Numbers in Java
The input that is returned from the input dialog box is a string. This implies that, if you enter a numeric value such as 123, it returns "123". Therefore in order to make it a number, you have to convert a string into a number to obtain the input as a number. 1. To convert a string into an int type value, then you need to use the parseInt method in the Integer class. Example: int myValue = Integer.parseInt(myString); where myString is a numeric string that had been entered such as "123". 2. To convert a string into a double value, then you use the parseDouble method in the Double class. Example: double myValue = Double.parseDouble(myString); where myString is a numeric string such as "123.45". The Integer and Double classes are both included in the java.lang package, and thus are automatically imported.

Example: '''DisplayCurrentTime.java import javax.swing.JOptionPane; public class DisplayCurrentTime { public static void main(String[] args) { // Obtain the total milliseconds long totalMilliseconds = System.currentTimeMillis; // Obtain the total seconds long totalSeconds = totalMilliseconds / 1000; // Compute the current second in the minute in the hour int currentSecond = (int)(totalSeconds % 60); // Obtain the total minutes long totalMinutes = totalSeconds / 60; // Compute the current minute in the hour int currentMinute = (int)(totalMinutes % 60); // Obtain the total hours long totalHours = totalMinutes / 60; // Compute the current hour int currentHour = (int)(totalHours % 24); // Display results String output = "Current time is " + currentHour + ":" + currentMinute + ":" + currentSecond + " GMT"; JOptionPane.showMessageDialog(null, output); } }

Getting Input from the Console
We have learned how you can obtain input from an input dialog box using the JOptionPane.showInputDialog method. Alternatively, you may also obtain input directly from the console. Java uses System.out statement to refer to the standard output device, and System.in statement to the standard input device. In Java, the output device is the console by default, and the default input device is the keyboard. To perform console output, you simply use the println method to output a primitive value or a string to the console. Console input is not directly supported in Java, but the Scanner class can be used to create an object that reads input from System.in. Example: Scanner myScanner = new Scanner(System.in); The syntax new Scanner(System.in) is used to create an object of the Scanner type. The syntax Scanner myScanner declares that myScanner is a variable whose type is Scanner. The whole line Scanner myScanner = new Scanner(System.in) creates a Scanner object and assigns its reference to the variable myScanner. Invoking a method on an object is basically to ask the object to perform a task. The Scanner object contains the following methods for reading an input: The examples below are statements that prompt the user to enter a double value from the console. System.out.print("Enter a double value: "); Scanner myScanner = new Scanner(System.in); double d = myScanner.nextDouble; NB: "The print method is identical to the println method except that println moves the cursor to the next line after displaying the string, but print does not advance the cursor to the next line when completed." Example: ScannerTest.java import java.util.Scanner; // Scanner is in java.util public class ScannerTest { public static void main(String args[]) { // Create a Scanner Scanner myScanner = new Scanner(System.in); // Prompt the user to enter an integer System.out.print("Enter an integer: "); int intValue = myScanner.nextInt; System.out.println("You entered the integer " + intValue);
 * 1) next: used for reading a string. A string is delimited by spaces.
 * 2) nextByte: used for reading an integer of the byte type.
 * 3) nextShort: used for reading an integer of the short type.
 * 4) nextInt: used for reading an integer of the int type.
 * 5) nextLong: for reading an integer of the long type.
 * 6) nextFloat: for reading a number of the float type.
 * 7) nextDouble: for reading a number of the double type.

// Prompt the user to enter a double value System.out.print("Enter a double value: "); double myValue = myScanner.nextDouble; System.out.println("You entered the double value "      + doubleValue);

// Prompt the user to enter a string System.out.print("Enter a string without space: "); String myString = myScanner.next; System.out.println("You entered the string " + string); } }

NB: "Using the console input has the benefit of allowing you to store the input values in a text file and pass the file from the command line using the command:" java ScannerTest < input.txt "where input.txt is a text file that contains the data that is the output of java ScannerTest < input.txt." "The output can also be saved into a file using the following command:" java ScannerTest < input.txt > out.txt NB: "By default, the Scanner object reads a string separated by whitespaces (' ', '\t', '\f', '\r', and '\n')." Example: ComputeLoanExample.java import java.util.Scanner; public class ComputeLoanExample { /** Main method */ public static void main(String[] args) { // Create a scanner for input Scanner input = new Scanner(System.in); // Enter yearly interest rate System.out.print("Enter yearly interest rate, for example 8.25: "); double annualInterestRate = input.nextDouble;

// Obtain monthly interest rate double monthlyInterestRate = annualInterestRate / 1200;

// Enter number of years System.out.print(      "Enter number of years as an integer, \nfor example 5: "); int numberOfYears = input.nextInt;

// Enter loan amount System.out.print("Enter loan amount, for example 120000.95: "); double loanAmount = input.nextDouble;

// Calculate payment double monthlyPayment = loanAmount * monthlyInterestRate / (1      – 1 / Math.pow(1 + monthlyInterestRate, numberOfYears * 12)); double totalPayment = monthlyPayment * numberOfYears * 12;

// Format to keep two digits after the decimal point monthlyPayment = (int)(monthlyPayment * 100) / 100.0; totalPayment = (int)(totalPayment * 100) / 100.0;

// Display results System.out.println("The monthly payment is " + monthlyPayment); System.out.println("The total payment is " + totalPayment); } }

Text I/O
A File object encapsulates the properties of a file or a path, but does not contain the methods for reading or writing data from or to a file. In order to perform I/O, you need to create objects using appropriate Java I/O classes. The objects contain the methods for reading and writing data from/to a file. This section introduces how to read/write strings and numeric values from/to a text file using the Scanner and PrintWriter classes.

Writing Data Using PrintWriter: The java.io.PrintWriter class can be used to write data to a text file. First, you have to create a PrintWriter object for a text file as follows: PrintWriter output = new PrintWriter(filename); Then, you can invoke the print, println, and printf methods on the PrintWriter object to write data to a file, gives an example that creates an instance of PrintWriter and writes two lines. Each line consists of first name (a string), middle name initial (a character), lastname (a string), and score (an integer). +PrintWriter(filename: String)		creates a print write object specified file. +print(s: String): void			writes a string. +print(c: char): void			writes a character. +print(cArray: char[ ]): void		writes an array of character. +print(i: int): void			writes an integer value +print(l: long): void			writes a long value +print(f: float): void			writes a float value +print(d: double): void			writes a double value +print(b: boolean): void			writes a boolean value Invoking the constructor new PrintWriter(String filename) will create a new file that is if the file does not exist. If the file already exists, then the current content in the file will be discarded. Invoking the constructor new PrintWriter(String filename) may throw an I/O exception. Java requires you to write the code to deal with this type of exception. The System.out.print and System.out.println methods can be used to write text to the console. System.out is a standard Java object for the console. Objects for writing text to files can be created by using print, println, and printf. The close method should be used to close the file. If this method is not invoked, the data may not be saved properly in the file.

To read from a file, create a Scanner for a file, using the following code: Scanner input = new Scanner(new File(filename));