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

Size: px
Start display at page:

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

Transcription

1 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 // 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).

2 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.

3 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.

4 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.

5 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);

6 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

7 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.

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

Handout 3 cs180 - Programming Fundamentals Fall 17 Page 1 of 6. Handout 3. Strings and String Class. Input/Output with JOptionPane. Handout 3 cs180 - Programming Fundamentals Fall 17 Page 1 of 6 Handout 3 Strings and String Class. Input/Output with JOptionPane. Strings In Java strings are represented with a class type String. Examples:

More information

Introduction to Computers and Engineering Problem Solving 1.00 / Fall 2004

Introduction to Computers and Engineering Problem Solving 1.00 / Fall 2004 Introduction to Computers and Engineering Problem Solving 1.00 / 1.001 Fall 2004 Problem Set 1 Due: 11AM, Friday September 17, 2004 Loan Calculator / Movie & Game Rental Store (0) [100 points] Introduction

More information

Java Programming Fundamentals - Day Instructor: Jason Yoon Website:

Java Programming Fundamentals - Day Instructor: Jason Yoon Website: Java Programming Fundamentals - Day 1 07.09.2016 Instructor: Jason Yoon Website: http://mryoon.weebly.com Quick Advice Before We Get Started Java is not the same as javascript! Don t get them confused

More information

More about JOptionPane Dialog Boxes

More about JOptionPane Dialog Boxes APPENDIX K More about JOptionPane Dialog Boxes In Chapter 2 you learned how to use the JOptionPane class to display message dialog boxes and input dialog boxes. This appendix provides a more detailed discussion

More information

CS 106 Introduction to Computer Science I

CS 106 Introduction to Computer Science I CS 106 Introduction to Computer Science I 06 / 02 / 2015 Instructor: Michael Eckmann Today s Topics Operators continue if/else statements User input Operators + when used with numeric types (e.g. int,

More information

A+ Computer Science -

A+ Computer Science - import java.util.scanner; or just import java.util.*; reference variable Scanner keyboard = new Scanner(System.in); object instantiation Scanner frequently used methods Name nextint() nextdouble() nextfloat()

More information

Lecture 11.1 I/O Streams

Lecture 11.1 I/O Streams 21/04/2014 Ebtsam AbdelHakam 1 OBJECT ORIENTED PROGRAMMING Lecture 11.1 I/O Streams 21/04/2014 Ebtsam AbdelHakam 2 Outline I/O Basics Streams Reading characters and string 21/04/2014 Ebtsam AbdelHakam

More information

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

Byte and Character Streams. Reading and Writing Console input and output Byte and Character Streams Reading and Writing Console input and output 1 I/O basics The io package supports Java s basic I/O (input/output) Java does provide strong, flexible support for I/O as it relates

More information

AP Computer Science Unit 1. Writing Programs Using BlueJ

AP Computer Science Unit 1. Writing Programs Using BlueJ AP Computer Science Unit 1. Writing Programs Using BlueJ 1. Open up BlueJ. Click on the Project menu and select New Project. You should see the window on the right. Navigate to wherever you plan to save

More information

CS 106 Introduction to Computer Science I

CS 106 Introduction to Computer Science I CS 106 Introduction to Computer Science I 01 / 29 / 2016 Instructor: Michael Eckmann Today s Topics Introduction operators (equality and relational) These all result in boolean if else statements User

More information

AP Computer Science Unit 1. Writing Programs Using BlueJ

AP Computer Science Unit 1. Writing Programs Using BlueJ AP Computer Science Unit 1. Writing Programs Using BlueJ 1. Open up BlueJ. Click on the Project menu and select New Project. You should see the window on the right. Navigate to wherever you plan to save

More information

Course PJL. Arithmetic Operations

Course PJL. Arithmetic Operations Outline Oman College of Management and Technology Course 503200 PJL Handout 5 Arithmetic Operations CS/MIS Department 1 // Fig. 2.9: Addition.java 2 // Addition program that displays the sum of two numbers.

More information

CT 229 Fundamentals of Java Syntax

CT 229 Fundamentals of Java Syntax CT 229 Fundamentals of Java Syntax 19/09/2006 CT229 New Lab Assignment Monday 18 th Sept -> New Lab Assignment on CT 229 Website Two Weeks for Completion Due Date is Oct 1 st Assignment Submission is online

More information

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

I/O in Java I/O streams vs. Reader/Writer. HW#3 due today Reading Assignment: Java tutorial on Basic I/O I/O 10-7-2013 I/O in Java I/O streams vs. Reader/Writer HW#3 due today Reading Assignment: Java tutorial on Basic I/O public class Swimmer implements Cloneable { public Date geteventdate() { return (Date)

More information

CS 106 Introduction to Computer Science I

CS 106 Introduction to Computer Science I CS 106 Introduction to Computer Science I 01 / 23 / 2015 Instructor: Michael Eckmann Today s Topics Questions? Comments? Review variables variable declaration assignment (changing a variable's value) using

More information

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

Week 12. Streams and File I/O. Overview of Streams and File I/O Text File I/O Week 12 Streams and File I/O Overview of Streams and File I/O Text File I/O 1 I/O Overview I/O = Input/Output In this context it is input to and output from programs Input can be from keyboard or a file

More information

First Java Program - Output to the Screen

First Java Program - Output to the Screen First Java Program - Output to the Screen These notes are written assuming that the reader has never programmed in Java, but has programmed in another language in the past. In any language, one of the

More information

Data Types and the while Statement

Data Types and the while Statement Session 2 Student Name Other Identification Data Types and the while Statement In this laboratory you will: 1. Learn about three of the primitive data types in Java, int, double, char. 2. Learn about the

More information

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

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics Java Programming, Sixth Edition 2-1 Chapter 2 Using Data At a Glance Instructor s Manual Table of Contents Overview Objectives Teaching Tips Quick Quizzes Class Discussion Topics Additional Projects Additional

More information

Introduction to Java Unit 1. Using BlueJ to Write Programs

Introduction to Java Unit 1. Using BlueJ to Write Programs Introduction to Java Unit 1. Using BlueJ to Write Programs 1. Open up BlueJ. Click on the Project menu and select New Project. You should see the window on the right. Navigate to wherever you plan to save

More information

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

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

More information

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

Project 1. Java Data types and input/output 1/17/2014. Primitive data types (2) Primitive data types in Java Java Data types and input/output Sharma Chakravarthy Information Technology Laboratory (IT Lab) Computer Science and Engineering Department The University of Texas at Arlington, Arlington, TX 76019 Email:

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

Full file at

Full file at Java Programming, Fifth Edition 2-1 Chapter 2 Using Data within a Program At a Glance Instructor s Manual Table of Contents Overview Objectives Teaching Tips Quick Quizzes Class Discussion Topics Additional

More information

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

Lab 5: Java IO 12:00 PM, Feb 21, 2018 CS18 Integrated Introduction to Computer Science Fisler, Nelson Contents Lab 5: Java IO 12:00 PM, Feb 21, 2018 1 The Java IO Library 1 2 Program Arguments 2 3 Readers, Writers, and Buffers 2 3.1 Buffering

More information

Internet Technology 2/7/2013

Internet Technology 2/7/2013 Sample Client-Server Program Internet Technology 02r. Programming with Sockets Paul Krzyzanowski Rutgers University Spring 2013 To illustrate programming with TCP/IP sockets, we ll write a small client-server

More information

Chapter 2: Using Data

Chapter 2: Using Data Chapter 2: Using Data TRUE/FALSE 1. A variable can hold more than one value at a time. F PTS: 1 REF: 52 2. The legal integer values are -2 31 through 2 31-1. These are the highest and lowest values that

More information

AP Programming - Chapter 3 Lecture. An Introduction

AP Programming - Chapter 3 Lecture. An Introduction page 1 of 28 An Introduction I. Identifiers - the name associated with a particular computer function or data object such as a variable, or a constant; Syntax rules: 1) Can only consist of letters (a-z,

More information

Program Fundamentals

Program Fundamentals Program Fundamentals /* HelloWorld.java * The classic Hello, world! program */ class HelloWorld { public static void main (String[ ] args) { System.out.println( Hello, world! ); } } /* HelloWorld.java

More information

1. Download the JDK 6, from

1. Download the JDK 6, from 1. Install the JDK 1. Download the JDK 6, from http://java.sun.com/javase/downloads/widget/jdk6.jsp. 2. Once the file is completed downloaded, execute it and accept the license agreement. 3. Select the

More information

Chapter 02: Using Data

Chapter 02: Using Data True / False 1. A variable can hold more than one value at a time. ANSWER: False REFERENCES: 54 2. The int data type is the most commonly used integer type. ANSWER: True REFERENCES: 64 3. Multiplication,

More information

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

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I BASIC COMPUTATION x public static void main(string [] args) Fundamentals of Computer Science I Outline Using Eclipse Data Types Variables Primitive and Class Data Types Expressions Declaration Assignment

More information

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

Learning objectives: Enhancing Classes. CSI1102: Introduction to Software Design. More about References. The null Reference. The this reference CSI1102: Introduction to Software Design Chapter 5: Enhancing Classes Learning objectives: Enhancing Classes Understand what the following entails Different object references and aliases Passing objects

More information

HST 952. Computing for Biomedical Scientists Lecture 8

HST 952. Computing for Biomedical Scientists Lecture 8 Harvard-MIT Division of Health Sciences and Technology HST.952: Computing for Biomedical Scientists HST 952 Computing for Biomedical Scientists Lecture 8 Outline Vectors Streams, Input, and Output in Java

More information

13 th Windsor Regional Secondary School Computer Programming Competition

13 th Windsor Regional Secondary School Computer Programming Competition SCHOOL OF COMPUTER SCIENCE 13 th Windsor Regional Secondary School Computer Programming Competition Hosted by The School of Computer Science, University of Windsor WORKSHOP I [ Overview of the Java/Eclipse

More information

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types

More information

Midterms Save the Dates!

Midterms Save the Dates! University of British Columbia CPSC 111, Intro to Computation Alan J. Hu (Using the Scanner and String Classes) Anatomy of a Java Program Readings This Week s Reading: Ch 3.1-3.8 (Major conceptual jump

More information

IT101. File Input and Output

IT101. File Input and Output IT101 File Input and Output IO Streams A stream is a communication channel that a program has with the outside world. It is used to transfer data items in succession. An Input/Output (I/O) Stream represents

More information

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

CSI Introduction to Software Design. Prof. Dr.-Ing. Abdulmotaleb El Saddik University of Ottawa (SITE 5-037) (613) x 6277 CSI 1102 Introduction to Software Design Prof. Dr.-Ing. Abdulmotaleb El Saddik University of Ottawa (SITE 5-037) (613) 562-5800 x 6277 elsaddik @ site.uottawa.ca abed @ mcrlab.uottawa.ca http://www.site.uottawa.ca/~elsaddik/

More information

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.

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. Java How to Program, 9/e Education, Inc. All Rights Reserved. } Covered in this chapter Classes Objects Methods Parameters double primitive type } Create a new class (GradeBook) } Use it to create an object.

More information

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

Tools : The Java Compiler. The Java Interpreter. The Java Debugger Tools : The Java Compiler javac [ options ] filename.java... -depend: Causes recompilation of class files on which the source files given as command line arguments recursively depend. -O: Optimizes code,

More information

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

Lecture 2. COMP1406/1006 (the Java course) Fall M. Jason Hinek Carleton University Lecture 2 COMP1406/1006 (the Java course) Fall 2013 M. Jason Hinek Carleton University today s agenda a quick look back (last Thursday) assignment 0 is posted and is due this Friday at 2pm Java compiling

More information

CSEN 202 Introduction to Computer Programming

CSEN 202 Introduction to Computer Programming CSEN 202 Introduction to Computer Programming Lecture 4: Iterations Prof. Dr. Slim Abdennadher and Dr Mohammed Abdel Megeed Salem, slim.abdennadher@guc.edu.eg German University Cairo, Department of Media

More information

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

A very simple program. Week 2: variables & expressions. Declaring variables. Assignments: examples. Initialising variables. Assignments: pattern School of Computer Science, University of Birmingham. Java Lecture notes. M. D. Ryan. September 2001. A very simple program Week 2: variables & expressions Variables, assignments, expressions, and types.

More information

AP Computer Science Unit 1. Programs

AP Computer Science Unit 1. Programs AP Computer Science Unit 1. Programs Open DrJava. Under the File menu click on New Java Class and the window to the right should appear. Fill in the information as shown and click OK. This code is generated

More information

CST141 Thinking in Objects Page 1

CST141 Thinking in Objects Page 1 CST141 Thinking in Objects Page 1 1 2 3 4 5 6 7 8 Object-Oriented Thinking CST141 Class Abstraction and Encapsulation Class abstraction is the separation of class implementation from class use It is not

More information

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

Variables of class Type. Week 8. Variables of class Type, Cont. A simple class: Week 8 Variables of class Type - Correction! Libraries/Packages String Class, reviewed Screen Input/Output, reviewed File Input/Output Coding Style Guidelines A simple class: Variables of class Type public

More information

Programming with Java

Programming with Java Programming with Java Data Types & Input Statement Lecture 04 First stage Software Engineering Dep. Saman M. Omer 2017-2018 Objectives q By the end of this lecture you should be able to : ü Know rules

More information

Introduction to Java. Nihar Ranjan Roy. https://sites.google.com/site/niharranjanroy/

Introduction to Java. Nihar Ranjan Roy. https://sites.google.com/site/niharranjanroy/ Introduction to Java https://sites.google.com/site/niharranjanroy/ 1 The Java Programming Language According to sun Microsystems java is a 1. Simple 2. Object Oriented 3. Distributed 4. Multithreaded 5.

More information

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

Project 1 Computer Science 2334 Spring 2016 This project is individual work. Each student must complete this assignment independently. Project 1 Computer Science 2334 Spring 2016 This project is individual work. Each student must complete this assignment independently. User Request: Create a simple movie data system. Milestones: 1. Use

More information

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

COT 3530: Data Structures. Giri Narasimhan. ECS 389; Phone: x3748 COT 3530: Data Structures Giri Narasimhan ECS 389; Phone: x3748 giri@cs.fiu.edu www.cs.fiu.edu/~giri/teach/3530spring04.html Evaluation Midterm & Final Exams Programming Assignments Class Participation

More information

Object-Oriented Programming Design. Topic : Streams and Files

Object-Oriented Programming Design. Topic : Streams and Files Electrical and Computer Engineering Object-Oriented Topic : Streams and Files Maj Joel Young Joel Young@afit.edu. 18-Sep-03 Maj Joel Young Java Input/Output Java implements input/output in terms of streams

More information

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

COMP-202: Foundations of Programming. Lecture 2: Java basics and our first Java program! Jackie Cheung, Winter 2016 COMP-202: Foundations of Programming Lecture 2: Java basics and our first Java program! Jackie Cheung, Winter 2016 Learn about cutting-edge research over lunch with cool profs January 18-22, 2015 11:30

More information

Chapter 5 Some useful classes

Chapter 5 Some useful classes Chapter 5 Some useful classes Lesson page 5-1. Numerical wrapper classes Activity 5-1-1 Wrapper-class Integer Question 1. False. A new Integer can be created, but its contents cannot be changed. Question

More information

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

Remedial Java - io 8/09/16. (remedial) Java. I/O. Anastasia Bezerianos 1 (remedial) Java anastasia.bezerianos@lri.fr I/O Anastasia Bezerianos 1 Input/Output Input Output Program We ve seen output System.out.println( some string ); Anastasia Bezerianos 2 Standard input/output!

More information

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

Last Time. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings University of British Columbia CPSC 111, Intro to Computation Alan J. Hu Writing a Simple Java Program Intro to Variables Readings Your textbook is Big Java (3rd Ed). This Week s Reading: Ch 2.1-2.5, Ch

More information

What did we talk about last time? Examples switch statements

What did we talk about last time? Examples switch statements Week 4 - Friday What did we talk about last time? Examples switch statements History of computers Hardware Software development Basic Java syntax Output with System.out.print() Mechanical Calculation

More information

4. Java Project Design, Input Methods

4. Java Project Design, Input Methods 4-1 4. Java Project Design, Input Methods Review and Preview You should now be fairly comfortable with creating, compiling and running simple Java projects. In this class, we continue learning new Java

More information

Program Elements -- Introduction

Program Elements -- Introduction Program Elements -- Introduction We can now examine the core elements of programming Chapter 3 focuses on: data types variable declaration and use operators and expressions decisions and loops input and

More information

Java Input/Output. 11 April 2013 OSU CSE 1

Java Input/Output. 11 April 2013 OSU CSE 1 Java Input/Output 11 April 2013 OSU CSE 1 Overview The Java I/O (Input/Output) package java.io contains a group of interfaces and classes similar to the OSU CSE components SimpleReader and SimpleWriter

More information

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

DOMjudge team manual. Summary. Reading and writing. Submitting solutions. Viewing scores, submissions, etc. judge DOMjudge team manual Summary /\ DOM DOM judge Here follows a short summary of the system interface. This is meant as a quick introduction, to be able to start using the system. It is, however, strongly

More information

CMSC 331 Second Midterm Exam

CMSC 331 Second Midterm Exam 1 20/ 2 80/ 331 First Midterm Exam 11 November 2003 3 20/ 4 40/ 5 10/ CMSC 331 Second Midterm Exam 6 15/ 7 15/ Name: Student ID#: 200/ You will have seventy-five (75) minutes to complete this closed book

More information

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

Lecture 6. Drinking. Nested if. Nested if s reprise. The boolean data type. More complex selection statements: switch. Examples. // Simple program to show how an if- statement works. import java.io.*; Lecture 6 class If { static BufferedReader keyboard = new BufferedReader ( new InputStreamReader( System.in)); public static void

More information

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

Course Content. Objectives of Lecture 22 File Input/Output. Outline of Lecture 22. CMPUT 102: File Input/Output Dr. Osmar R. Structural Programming and Data Structures Winter 2000 CMPUT 102: Input/Output Dr. Osmar R. Zaïane Course Content Introduction Objects Methods Tracing Programs Object State Sharing resources Selection

More information

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

Introduction to Classes and Objects Pearson Education, Inc. All rights reserved. 1 3 Introduction to Classes and Objects 2 You will see something new. Two things. And I call them Thing One and Thing Two. Dr. Theodor Seuss Geisel Nothing can have value without being an object of utility.

More information

CS 231 Data Structures and Algorithms, Fall 2016

CS 231 Data Structures and Algorithms, Fall 2016 CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard

More information

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

09-1. CSE 143 Java GREAT IDEAS IN COMPUTER SCIENCE. Overview. Data Representation. Representation of Primitive Java Types. Input and Output. CSE 143 Java Streams Reading: 19.1, Appendix A.2 GREAT IDEAS IN COMPUTER SCIENCE REPRESENTATION VS. RENDERING 4/28/2002 (c) University of Washington 09-1 4/28/2002 (c) University of Washington 09-2 Topics

More information

Simple Java Reference

Simple Java Reference Simple Java Reference This document provides a reference to all the Java syntax used in the Computational Methods course. 1 Compiling and running... 2 2 The main() method... 3 3 Primitive variable types...

More information

Chapter 2: Using Data

Chapter 2: Using Data Chapter 2: Using Data TRUE/FALSE 1. A variable can hold more than one value at a time. F PTS: 1 REF: 52 2. The legal integer values are -2 31 through 2 31-1. These are the highest and lowest values that

More information

VARIABLES, DATA TYPES,

VARIABLES, DATA TYPES, 1-59863-275-2_CH02_31_05/23/06 2 C H A P T E R VARIABLES, DATA TYPES, AND SIMPLE IO In this chapter, you learn how to use variables, data types, and standard input/output (IO) to create interactive applications.

More information

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

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics WIT COMP1000 Java Basics Java Origins Java was developed by James Gosling at Sun Microsystems in the early 1990s It was derived largely from the C++ programming language with several enhancements Java

More information

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

Project #1 rev 2 Computer Science 2334 Fall 2013 This project is individual work. Each student must complete this assignment independently. Project #1 rev 2 Computer Science 2334 Fall 2013 This project is individual work. Each student must complete this assignment independently. User Request: Create a simple magazine data system. Milestones:

More information

Getting started with Java

Getting started with Java Getting started with Java Magic Lines public class MagicLines { public static void main(string[] args) { } } Comments Comments are lines in your code that get ignored during execution. Good for leaving

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

AP CS Unit 3: Control Structures Notes

AP CS Unit 3: Control Structures Notes AP CS Unit 3: Control Structures Notes The if and if-else Statements. These statements are called control statements because they control whether a particular block of code is executed or not. Some texts

More information

Midterms Save the Dates!

Midterms Save the Dates! University of British Columbia CPSC 111, Intro to Computation Alan J. Hu Primitive Data Types Arithmetic Operators Readings Your textbook is Big Java (3rd Ed). This Week s Reading: Ch 2.1-2.5, Ch 4.1-4.2.

More information

Lecture 4: Exceptions. I/O

Lecture 4: Exceptions. I/O Lecture 4: Exceptions. I/O Outline Access control. Class scope Exceptions I/O public class Malicious { public static void main(string[] args) { maliciousmethod(new CreditCard()); } static void maliciousmethod(creditcard

More information

CS 177 Recitation. Week 1 Intro to Java

CS 177 Recitation. Week 1 Intro to Java CS 177 Recitation Week 1 Intro to Java Questions? Computers Computers can do really complex stuff. How? By manipulating data according to lists of instructions. Fundamentally, this is all that a computer

More information

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types and

More information

An overview of Java, Data types and variables

An overview of Java, Data types and variables An overview of Java, Data types and variables Lecture 2 from (UNIT IV) Prepared by Mrs. K.M. Sanghavi 1 2 Hello World // HelloWorld.java: Hello World program import java.lang.*; class HelloWorld { public

More information

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

COMP 213. Advanced Object-oriented Programming. Lecture 19. Input/Output COMP 213 Advanced Object-oriented Programming Lecture 19 Input/Output Input and Output A program that read no input and produced no output would be a very uninteresting and useless thing. Forms of input/output

More information

Computer Science is...

Computer Science is... Computer Science is... Automated Software Verification Using mathematical logic, computer scientists try to design tools to automatically detect runtime and logical errors in huge, complex programs. Right:

More information

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

Introduction to Classes and Objects Pearson Education, Inc. All rights reserved. 1 3 Introduction to Classes and Objects 2 You will see something new. Two things. And I call them Thing One and Thing Two. Dr. Theodor Seuss Geisel Nothing can have value without being an object of utility.

More information

Selected Sections of Applied Informatics LABORATORY 0

Selected Sections of Applied Informatics LABORATORY 0 SSAI 2018Z: Class 1. Basics of Java programming. Page 1 of 6 Selected Sections of Applied Informatics LABORATORY 0 INTRODUCTION TO JAVA PROGRAMMING. BASIC LANGUAGE INSTRUCTIONS. CONSOLE APPLICATION. CONDITION,

More information

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

Software Practice 1 - Basic Grammar Basic Syntax Data Type Loop Control Making Decision Software Practice 1 - Basic Grammar Basic Syntax Data Type Loop Control Making Decision Prof. Hwansoo Han T.A. Minseop Jeong T.A. Wonseok Choi 1 Java Program //package details public class ClassName {

More information

Simple Java Input/Output

Simple Java Input/Output Simple Java Input/Output Prologue They say you can hold seven plus or minus two pieces of information in your mind. I can t remember how to open files in Java. I ve written chapters on it. I ve done it

More information

File Processing in Java

File Processing in Java What is File I/O? File Processing in Java I/O is an abbreviation for input and output. Input is data coming in at runtime. Input come sin through a mouse, keyboard, touchscreen, microphone and so on. Output

More information

Classes Basic Overview

Classes Basic Overview Final Review!!! Classes and Objects Program Statements (Arithmetic Operations) Program Flow String In-depth java.io (Input/Output) java.util (Utilities) Exceptions Classes Basic Overview A class is a container

More information

Lab # 2. For today s lab:

Lab # 2. For today s lab: 1 ITI 1120 Lab # 2 Contributors: G. Arbez, M. Eid, D. Inkpen, A. Williams, D. Amyot 1 For today s lab: Go the course webpage Follow the links to the lab notes for Lab 2. Save all the java programs you

More information

CHAPTER 7 ARRAYS: SETS OF SIMILAR DATA ITEMS

CHAPTER 7 ARRAYS: SETS OF SIMILAR DATA ITEMS CHAPTER 7 ARRAYS: SETS OF SIMILAR DATA ITEMS Computers process information and usually they need to process masses of information. In previous chapters we have studied programs that contain a few variables

More information

Pace University. Fundamental Concepts of CS121 1

Pace University. Fundamental Concepts of CS121 1 Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction

More information

Controls Structure for Repetition

Controls Structure for Repetition Controls Structure for Repetition So far we have looked at the if statement, a control structure that allows us to execute different pieces of code based on certain conditions. However, the true power

More information

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

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java CS121/IS223 Object Reference Variables Dr Olly Gotel ogotel@pace.edu http://csis.pace.edu/~ogotel Having problems? -- Come see me or call me in my office hours -- Use the CSIS programming tutors Agenda

More information

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

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI CSCI 2010 Principles of Computer Science Data and Expressions 08/09/2013 CSCI 2010 1 Data Types, Variables and Expressions in Java We look at the primitive data types, strings and expressions that are

More information

COMP 202 Java in one week

COMP 202 Java in one week COMP 202 Java in one week... Continued CONTENTS: Return to material from previous lecture At-home programming exercises Please Do Ask Questions It's perfectly normal not to understand everything Most of

More information

Introduction to Classes and Objects

Introduction to Classes and Objects 1 2 Introduction to Classes and Objects You will see something new. Two things. And I call them Thing One and Thing Two. Dr. Theodor Seuss Geisel Nothing can have value without being an object of utility.

More information

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

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1 topics: introduction to java, part 1 cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 cis20.1-fall2007-sklar-leci.2 1 Java. Java is an object-oriented language: it is

More information

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

EXCEPTION HANDLING. // code that may throw an exception } catch (ExceptionType parametername) { EXCEPTION HANDLING We do our best to ensure program correctness through a rigorous testing and debugging process, but that is not enough. To ensure reliability, we must anticipate conditions that could

More information

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

Introduction to Computation and Problem Solving. Class 25: Error Handling in Java. Prof. Steven R. Lerman and Dr. V. Judson Harward. Introduction to Computation and Problem Solving Class 25: Error Handling in Java Prof. Steven R. Lerman and Dr. V. Judson Harward Goals In this session we are going to explore better and worse ways to

More information

CHAPTER 7 OBJECTS AND CLASSES

CHAPTER 7 OBJECTS AND CLASSES CHAPTER 7 OBJECTS AND CLASSES OBJECTIVES After completing Objects and Classes, you will be able to: Explain the use of classes in Java for representing structured data. Distinguish between objects and

More information