Reading Strings-Tiny Text Editor Reading Console Input:Scanner Writing Console Output
The document discusses different ways to perform input and output operations in Java, including:
1) Reading input from the console using a Scanner, which can read different data types like numbers, strings, and converts them to their binary forms.
2) Writing output to the console can be done with println() and print() methods, but PrintWriter is recommended for real applications since it allows easier internationalization.
3) PrintWriter is initialized with System.out and a flush parameter, and supports print() and println() like System.out to write to the console.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0 ratings0% found this document useful (0 votes)
47 views31 pages
Reading Strings-Tiny Text Editor Reading Console Input:Scanner Writing Console Output
The document discusses different ways to perform input and output operations in Java, including:
1) Reading input from the console using a Scanner, which can read different data types like numbers, strings, and converts them to their binary forms.
2) Writing output to the console can be done with println() and print() methods, but PrintWriter is recommended for real applications since it allows easier internationalization.
3) PrintWriter is initialized with System.out and a flush parameter, and supports print() and println() like System.out to write to the console.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 31
Reading Strings- Tiny text editor
Reading Console Input:Scanner
Writing Console Output Reading Strings- Tiny text editor • The next example creates a Tiny text editor. • It creates an array of String objects and then reads in lines of text, storing each line in the array. • It will read up to 100 lines or until you enter “stop.” • It uses a BufferedReader to read from the console. A tiny editor // A tiny editor. import java.io.*; class TinyEdit { public static void main(String args[]) throws IOException { Reading Strings-Cont… BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str[] = new String[100]; System.out.println("Enter lines of text."); System.out.println("Enter 'stop' to quit."); Reading Strings-Cont… for(int i=0; i<100; i++) { str[i] = br.readLine(); if(str[i].equals("stop")) break; } Reading Strings-Cont… System.out.println("\nHere is your file:"); // display the lines for(int i=0; i<100; i++) { if(str[i].equals("stop")) break; System.out.println(str[i]); } } } Reading Strings-Cont… Here is a sample run: Enter lines of text. Enter 'stop' to quit. This is line one. This is line two. Java makes working with strings easy. Just create String objects. stop Reading Strings-Cont… Here is your file: This is line one. This is line two. Java makes working with strings easy. Just create String objects. Reading Console Input: Scanner • Scanner can be used to read input from the console, a file, a string, or any source that implements the Readable interface or ReadableByteChannel. • Scanner reads formatted input and converts it into its binary form. • Using scanner, it is easy to read all types of numeric values, strings, and other types of data • For example, you can use Scanner to read a number from the keyboard and assign its value to a variable. // Use Scanner to compute an average of the values. import java.util.*; class AvgNums { public static void main(String args[]) { Scanner conin = new Scanner(System.in); int count = 0; double sum = 0.0; System.out.println("Enter numbers"); // Read and sum numbers. while(conin.hasNext()) { if(conin.hasNextDouble()) { sum += conin.nextDouble(); count++; } else { String str = conin.next(); if(str.equals("done")) break; else { System.out.println("Data format error."); return; } } } System.out.println("Average is " + sum / count); } } The program reads numbers from the keyboard, summing them in the process, until the user enters the string “done”. It then stops input and displays the average of the numbers. Here is a sample run: Enter numbers. 1.2 2 3.4 4 done Average is 2.65 Analysis of the program The program reads numbers until it encounters a token that does not represent a valid double value. When this occurs, it confirms that the token is the string “done”. If it is, the program terminates normally. Otherwise, it displays an error. Analysis of the program Notice that the numbers are read by calling nextDouble( ). This method reads any number that can be converted into a double value, including an integer value, such as 2, and a floating-point value like 3.4. Thus, a number read by nextDouble( ) need not specify a decimal point. This same general principle applies to all next methods. They will match and read any data format that can represent the type of value being requested. Writing Console Output Writing Console Output-Cont... • Console output is most easily accomplished with print( ) and println( ), described earlier, which are used in most of the examples in this book. • These methods are defined by the class PrintStream (which is the type of object referenced by System.out). • Even though System.out is a byte stream, using it for simple program output is still acceptable. • Because PrintStream is an output stream derived from OutputStream, it also implements the low-level method write( ). • Thus, write( ) can be used to write to the console. • The simplest form of write( ) defined by PrintStream is shown here: void write(int byteval) • This method writes to the stream the byte specified by byteval. • Although byteval is declared as an integer, only the low-order eight bits are written. • Here is a short example that uses write( ) to output the character “A” followed by a newline to the screen: LTC:Writing Console Output // Demonstrate System.out.write(). class WriteDemo { public static void main(String args[]) { int b; b = 'A'; System.out.write(b); System.out.write('\n'); } } • You will not often use write( ) to perform console output (although doing so might be useful in some situations), because print( ) and println( ) are substantially easier to use. The Print Writer Class The PrintWriter Class • Although using System.out to write to the console is acceptable, its use is recommended mostly for debugging purposes or for sample programs. • For real-world programs, the recommended method of writing to the console when using Java is through a PrintWriter stream. The PrintWriter Class-cont... • PrintWriter is one of the character-based classes. • Using a character-based class for console output makes it easier to internationalize your program. • PrintWriter defines several constructors. The one we will use is shown here: PrintWriter(OutputStream outputStream, boolean flushOnNewline) The PrintWriter Class-cont... • Here, outputStream is an object of type OutputStream, and flushOnNewline controls whether Java flushes the output stream every time a println( ) method is called. • If flushOnNewline is true, flushing automatically takes place. • If false, flushing is not automatic. The PrintWriter Class-cont... • PrintWriter supports the print( ) and println( ) methods for all types including Object. • Thus, you can use these methods in the same way as they have been used with System.out. • If an argument is not a simple type, the PrintWriter methods call the object’s toString( ) method and then print the result. The PrintWriter Class-cont... • To write to the console by using a PrintWriter, specify System.out for the output stream and flush the stream after each newline. • For example, this line of code creates a PrintWriter that is connected to console output: PrintWriter pw = new PrintWriter(System.out, true); LTC:The PrintWriter Class // Demonstrate PrintWriter import java.io.*; public class PrintWriterDemo { public static void main(String args[]) { PrintWriter pw = new PrintWriter(System.out, true); pw.println("This is a string"); int i = -7; pw.println(i); double d = 4.5e-7; pw.println(d); } } The output from this program is shown here: This is a string -7 4.5E-7 The PrintWriter Class-cont... • Remember, there is nothing wrong with using System.out to write simple text output to the console when you are learning Java or debugging your programs. • However, using a PrintWriter will make your real- world applications easier to internationalize. • Because no advantage is gained by using a PrintWriter in the sample programs shown in this book, we will continue to use System.out to write to the console. End of Class