Lesson 3: Accepting User Input and Using Different Methods for Output

Similar documents
Handout 3 cs180 - Programming Fundamentals Fall 17 Page 1 of 6. Handout 3. Strings and String Class. Input/Output with JOptionPane.

Introduction to Computers and Engineering Problem Solving 1.00 / Fall 2004

Java Programming Fundamentals - Day Instructor: Jason Yoon Website:

More about JOptionPane Dialog Boxes

CS 106 Introduction to Computer Science I

A+ Computer Science -

Lecture 11.1 I/O Streams

Byte and Character Streams. Reading and Writing Console input and output

AP Computer Science Unit 1. Writing Programs Using BlueJ

CS 106 Introduction to Computer Science I

AP Computer Science Unit 1. Writing Programs Using BlueJ

Course PJL. Arithmetic Operations

CT 229 Fundamentals of Java Syntax

I/O in Java I/O streams vs. Reader/Writer. HW#3 due today Reading Assignment: Java tutorial on Basic I/O

CS 106 Introduction to Computer Science I

Week 12. Streams and File I/O. Overview of Streams and File I/O Text File I/O

First Java Program - Output to the Screen

Data Types and the while Statement

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

Introduction to Java Unit 1. Using BlueJ to Write Programs

Key Concept: all programs can be broken down to a combination of one of the six instructions Assignment Statements can create variables to represent

Project 1. Java Data types and input/output 1/17/2014. Primitive data types (2) Primitive data types in Java

Full file at

Full file at

Lab 5: Java IO 12:00 PM, Feb 21, 2018

Internet Technology 2/7/2013

Chapter 2: Using Data

AP Programming - Chapter 3 Lecture. An Introduction

Program Fundamentals

1. Download the JDK 6, from

Chapter 02: Using Data

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

Learning objectives: Enhancing Classes. CSI1102: Introduction to Software Design. More about References. The null Reference. The this reference

HST 952. Computing for Biomedical Scientists Lecture 8

13 th Windsor Regional Secondary School Computer Programming Competition

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Midterms Save the Dates!

IT101. File Input and Output

CSI Introduction to Software Design. Prof. Dr.-Ing. Abdulmotaleb El Saddik University of Ottawa (SITE 5-037) (613) x 6277

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension.

Tools : The Java Compiler. The Java Interpreter. The Java Debugger

Lecture 2. COMP1406/1006 (the Java course) Fall M. Jason Hinek Carleton University

CSEN 202 Introduction to Computer Programming

A very simple program. Week 2: variables & expressions. Declaring variables. Assignments: examples. Initialising variables. Assignments: pattern

AP Computer Science Unit 1. Programs

CST141 Thinking in Objects Page 1

Variables of class Type. Week 8. Variables of class Type, Cont. A simple class:

Programming with Java

Introduction to Java. Nihar Ranjan Roy.

Project 1 Computer Science 2334 Spring 2016 This project is individual work. Each student must complete this assignment independently.

COT 3530: Data Structures. Giri Narasimhan. ECS 389; Phone: x3748

Object-Oriented Programming Design. Topic : Streams and Files

COMP-202: Foundations of Programming. Lecture 2: Java basics and our first Java program! Jackie Cheung, Winter 2016

Chapter 5 Some useful classes

Remedial Java - io 8/09/16. (remedial) Java. I/O. Anastasia Bezerianos 1

Last Time. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

What did we talk about last time? Examples switch statements

4. Java Project Design, Input Methods

Program Elements -- Introduction

Java Input/Output. 11 April 2013 OSU CSE 1

DOMjudge team manual. Summary. Reading and writing. Submitting solutions. Viewing scores, submissions, etc.

CMSC 331 Second Midterm Exam

Lecture 6. Drinking. Nested if. Nested if s reprise. The boolean data type. More complex selection statements: switch. Examples.

Course Content. Objectives of Lecture 22 File Input/Output. Outline of Lecture 22. CMPUT 102: File Input/Output Dr. Osmar R.

Introduction to Classes and Objects Pearson Education, Inc. All rights reserved.

CS 231 Data Structures and Algorithms, Fall 2016

09-1. CSE 143 Java GREAT IDEAS IN COMPUTER SCIENCE. Overview. Data Representation. Representation of Primitive Java Types. Input and Output.

Simple Java Reference

Chapter 2: Using Data

VARIABLES, DATA TYPES,

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

Project #1 rev 2 Computer Science 2334 Fall 2013 This project is individual work. Each student must complete this assignment independently.

Getting started with Java

Introduction to Programming Using Java (98-388)

AP CS Unit 3: Control Structures Notes

Midterms Save the Dates!

Lecture 4: Exceptions. I/O

CS 177 Recitation. Week 1 Intro to Java

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

An overview of Java, Data types and variables

COMP 213. Advanced Object-oriented Programming. Lecture 19. Input/Output

Computer Science is...

Introduction to Classes and Objects Pearson Education, Inc. All rights reserved.

Selected Sections of Applied Informatics LABORATORY 0

Software Practice 1 - Basic Grammar Basic Syntax Data Type Loop Control Making Decision

Simple Java Input/Output

File Processing in Java

Classes Basic Overview

Lab # 2. For today s lab:

CHAPTER 7 ARRAYS: SETS OF SIMILAR DATA ITEMS

Pace University. Fundamental Concepts of CS121 1

Controls Structure for Repetition

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

COMP 202 Java in one week

Introduction to Classes and Objects

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1

EXCEPTION HANDLING. // code that may throw an exception } catch (ExceptionType parametername) {

Introduction to Computation and Problem Solving. Class 25: Error Handling in Java. Prof. Steven R. Lerman and Dr. V. Judson Harward.

CHAPTER 7 OBJECTS AND CLASSES

Transcription:

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.