Lesson 3: Accepting User Input and Using Different Methods for Output Introduction So far, you have had an overview of the basics in Java. This document will discuss how to put some power in your program by accepting user input and displaying the output in other ways. This document is going to discuss how to accept user input by using the java.io.* library and the javax.swing.* library. Try both of these ways. When you are writing your programs, you can use the method of your choice. NOTE: These methods apply to applications only. Accepting Input There are many ways that you can accept user input in your program. You are going two simple ways of accepting user input in your program. Method 1: Using the java.io library This was the original way to accept input from the user, and the capability is still available in the latest version of Java. By using this method, you are implementing a console interface. Console interface is also known as a text interface because the user sees a text message instructing him or her on what he or she needs to do. Let s take a look at an example program using this method. This program is called StringTestIO.java. Note that at first glance, it s a bit complicated. I ll explain how the code works, which (I hope) will make it easier to understand. Also note that each line in the code has been numbered for easier reference. If you were typing this code in a text editor, you would not type the line numbers. 1 1. // StringTestIO.java - simple input/output program using the io library 2. import java.io.*; // required 3. public class StringTestIO 4. { 5. // you need the "throws IOException" because the classes for the io library 6. // throw errors 7. public static void main(string[] arg) throws IOException 8. { 9. InputStreamReader isr; // this opens for keyboard input 10. BufferedReader keyboard; // this "reads" the information 11. String inputline; 1 Note that this example is similar to the StringTestIO.java program that s available for download on this site. There are two things that you will need to change in the code that s available on the site. First, make the class public (like in line 3 of the example). Second, move the square brackets from after the arg to after the String (like in line 7).
12. isr = new InputStreamReader(System.in); 13. keyboard = new BufferedReader(isr); 14. inputline = keyboard.readline(); 15. System.out.println(inputLine); 16. } 17. } The breakdown: The first line (line 1) is a comment that just indicates what this program does. Remember that there are more than one way to indicate comments in Java. In order to be able to use the classes to allow our program to accept user input, we need to import the java library java.io.* (line 2). The statement import java.io.*; says let me use all of the classes that are a part of the java.io library. The third line is the declaration of the class StringTestIO. Note that this class has the exact same name as the file name even to the case. Remember that java is case sensitive: stringtestio is not the same as StringTestIO. The fourth and seventeenth line of the code indicate the braces that start and finish the block. Anything that falls in these braces are associated with the class StringTestIO. If you get confused by how the braces should point, remember that if you speak English, you read left-to-right. You start reading from the left (the starting bracket of the class/method points to the left), and you finish reading at the right (the ending bracket of the class/method points to the right). Lines 5 and 6 is a comment that will explain why we are writing line 7 the way we are. In the last lesson, we learned that the main method tells the Java interpreter where to start. If you also remember from the last lesson (and in the Dr. Kjell reading assignment), we wrote the method as public static void main(string[] args). We have to add the clause throws IOException after this method because the java.io methods are programmed to throw an error. We will learn about this in more detail in the February 25 th lesson. For now, all you need to know is if you don t add this clause in your program when using the java.io library for input, your program will not compile. Lines 8 and 16 are the brackets that indicate the start and finish of the block of code that is associated with the main() method. As you are probably learning by now, Java is a class-based programming language, and virtually everything that you do in Java is a class. The class InputStreamReader is a class that is used for keyboard (or other media) input (line 9). The BufferedReader class allows us to process the input more efficiently (line 10). What this does is it allows us to work from memory rather than from direct media access. We will learn about this in more detail in the February 25 th lesson. For now, all you need to know is that you need these two classes to perform user input from the keyboard. Line 11 is declaring an object variable of String called inputline. Remember that the String class is not a primitive data type it is a class created by the developers of the Java language to allow us to work with strings without extra coding effort. Basically, String is an array of chars. Line 12 creates an instance of the InputStreamReader class. We pass the parameter of System.in. Remember that System.out represents our primary output device (usually the monitor). System.in represents our primary input device (usually our keyboard). In other words, this statement is saying take what the user is typing and put it in this class. Line 13 is putting that class in the buffer (BufferedReader). Line 14 officially processes what the user enters. The readline() method of the keyboard (instance of the BufferedReader class) reads the line and returns a String as the result of that read. The carriage return (a.k.a when the user hits the enter key) indicates the end of the line. Line 15 just returns what the user typed by using the System.out.println() method. What this does is it will print out the statement on the screen and go to the next line.
Here is the output of this program: My name is Jennifer. My name is Jennifer. When I ran this program, I got a blinking cursor. I typed, My name is Jennifer. When I pressed Enter, it repeated what I typed. The Challengers: Another Way to Write This Same Program If you are used to the above example, here s another way that you can write this same program. Without all of the comments explaining the actions, you ll probably notice that the program is smaller. Don t attempt this until you are comfortable with the previously mentioned example. 1. // StringTestIO.java - simple input/output program using the io library 2. import java.io.*; // required 3. public class StringTestIO 4. { 5. // you need the "throws IOException" because the classes for the io library 6. // throw errors 7. public static void main(string[] arg) throws IOException 8. { 9. // this demonstrates how you can declare the variable and assign a value of the variable at 10. // declaration time. What you are doing is declaring an anonymous instance of the InputStreamReader 11. // class, and you are assigning a value of the anonymous InputStreamReader class of System.in. Finally, 12. // you are assigning a value of the BufferedReader instance (keyboard) as whatever the value of the anonymous 13. // InputStreamReader class is. 14. BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in)); 15. String inputline; 16. inputline = keyboard.readline(); 17. System.out.println(inputLine); 18. } 19. } Method 2: Using the javax.swing library The release of Java version 1.2 (a.k.a Java 2) introduced the Java programmer to the Swing libraries. Swing is a group of libraries that allow us to create graphical interfaces in our programs. We are going to learn how to use the Swing libraries to accept user input, and we are also going to learn how to display the output in a graphical manner. Let s take a look at an example program using this method. This program is called StringTest.java. In my opinion, this is the easier of the two methods. However, you may want to practice Method 1 because these are the same classes and concepts that we will be using for file processing. Note that each line in the code has been numbered for easier reference. If you were typing this code in a text editor, you would not type the line numbers.
1. // StringTest.java - a sample input/output program using the Swing components 2. import javax.swing.*; // required library for Swing 3. public class StringTest 4. { 5. public static void main(string[] args) 6. { 7. // showinputdialog displays an input box. 8. // showmessagedialog displays a "Ok" box. 9. String s = JOptionPane.showInputDialog("Enter something"); 10. JOptionPane.showMessageDialog(null, s); 11. System.exit(0); // you MUST have this or you will have a "blinking prompt" 12. } 13. } The breakdown: Line 1 indicates the name of the program. In order to be able to use the classes to allow our program to create graphical interfaces, we need to import the java library javax.swing.* (line 2). The statement import javax.swing.*; says let me use all of the classes that are a part of the javax.swing library. The third line is the declaration of the class StringTest. Note that this class has the exact same name as the file name even to the case. Remember that java is case sensitive: stringtest is not the same as StringTest. The fourth and thirteeth line of the code indicate the braces that start and finish the block. Anything that falls in these braces is associated with the class StringTest. Line 5 is the creation of the main method. Note that we do not need to add the clause throws IOException for this method. Lines 6 and 12 are the brackets that indicate the block of code associated with the main method Lines 7 and 8 are comments indicating what Lines 9 and 10 are. In line 9, we are using the class and method JOptionPane.showInputDialog( Enter something );. The JOptionPane is creating a small window for input and output. The showinputdialog method creates an input box for the user to enter the information, and it returns a String, or what the user entered in the box. The text that falls in between the parentheses is the message or instruction that the user will see. Note that we are assigning the object variable of s (String) as this class. Java will first display the message to the user. When the user enters the data and clicks on OK, it will return a String value. That String value will be assigned to the variable s. In line 10, we are creating an output box for display. The JOptionPane.showMessageDialog(null, s); statement is creating a box with an OK button. The first parameter in the parentheses (null) indicates that the window will appear in the system. The second parameter in the parentheses (s) indicates what will be displayed in the box. So in our example, the value of s will be displayed in the box. Special note about showmessagedialog: you can only display objects in this class. You cannot display primitive data types (int, double, float, char, byte, boolean, long, short) in this box. You can display primitive data types if a) you combine them with a string literal, such as The value of x is: + x, or b) you put that primitive data type in its wrapper class. We will learn about the wrapper classes in more detail later in the document.
Line 11 is important. Without this line, your operating system will think that your program is still running. What you will see is a blinking prompt. In order to send a message to your operating system that your program is finished, you add the line System.exit(0); Here is the output of the program: When I clicked OK, here s what I got: The Wrapper Classes in More Detail We have been introduced to accepting user input. We have also noticed that regardless of what method we use for accepting user input, the method will return a String. So what if we want to accept a primitive data type, such as an int or a double? You need to use one of the wrapper classes to convert the String value to the primitive data type, or the number. The developers of the Java language created corresponding classes for the primitive data types, called wrapper classes, that we can use in case we need to pass a primitive data type value to a method that accepts only classes, like the showmessagedialog method of the JOptionPane. Conversely, these wrapper classes also allow us to translate a class to a primitive data type. Below we are going to see an example of translating a String to various primitive data types. 1. import javax.swing.*; // required library for Swing 2. public class InputLab 3. { 4. public static void main(string[] args) 5. { 6. int x; 7. double y; 8. String z; 9. String input; 10. // showinputdialog displays an input box. 11. // showmessagedialog displays a "Ok" box. 12. z = JOptionPane.showInputDialog("Enter a sentence."); 13. JOptionPane.showMessageDialog(null, z); 14. input = JOptionPane.showInputDialog("Enter an integer"); 15. x = Integer.parseInt(input);
16. JOptionPane.showMessageDialog(null, "Here's your number: " + x); 17. input = JOptionPane.showInputDialog("Enter a double"); 18. y = Double.parseDouble(input); 19. JOptionPane.showMessageDialog(null, "Here's your number: " + y); 20. System.exit(0); // you MUST have this or you will have a "blinking prompt" 21. } 22. } If you notice in line 15, we are using Integer.parseInt(input);. This method will translate the string value in the variable input, and return an int value. We are assigning that to the variable x (declared as an int in line 6). Here is something to note: if the value of input does not contain an integer numeric value, your program will return a bunch of lines, called an exception stack trace, indicating that something went wrong in your program. In particular, that exception will be called NumberFormatException. For example, if input contains values such as Jennifer, 98.6, or 1hello, your program will generate the exception stack trace. In line 17, we are using Double.parseDouble(input);. This method will translate the string value in the variable input, and return a double value. We are assigning that to the variable y (declared as a double in line 7). Just like with Integer.parseInt(input), if the value of input does not contain a decimal numeric value, your program will generate the NumberFormatException stack trace. Below is a chart of translating a String to a corresponding primitive data type. There is no special translation method for the Character wrapper class. However, we are going to learn about the String class and how we can get a char data type from the String next week. Assuming that you have a String variable called somevalue.. To translate to an.. Use int Integer.parseInt(someValue); double Double.parseDouble(someValue); float Float.parseFloat(someValue); short Short.parseShort(someValue); long Long.parseLong(someValue); boolean Boolean.getBoolean(someValue); Below we are going to see an example of translating a primitive data type to an object such as a String: 1. import javax.swing.*; // required library for Swing 2. public class InputLab2 3. { 4. public static void main(string[] args) 5. { 6. int x = 7; 7. String output; 8. // we declare an instance of the Integer class. We pass the primitive data type as the value 9. Integer xclass = new Integer(x); 10. // the tostring() method converts the value to a string
11. output = xclass.tostring(); 12. JOptionPane.showMessageDialog(null, output); 13. System.exit(0); // you MUST have this or you will have a "blinking prompt" 14. } 15. } As you notice in line 9, we declare an instance of the Integer wrapper class, and we pass the int value to that declaration. In line 11, we translate that variable to a String value by using the tostring() method. You would follow this same logic for the Double, Float, Short, Long and Boolean wrapper classes as well. The bottom line: 1. Declare an instance of the wrapper class 2. Pass the primitive data type as the value 3. To convert to a string, use the tostring() method.