CS 201 Lecture 7: John Hurley Summer 2012 Cal State LA.

Slides:



Advertisements
Similar presentations
CS 106 Introduction to Computer Science I 09 / 13 / 2006 Instructor: Michael Eckmann.
Advertisements

Primitive Data Types and Operations. Introducing Programming with an Example public class ComputeArea { /** Main method */ public static void main(String[]
Using JOptionPanes for graphical communication with our programs. Pages Horstmann 139.
Exceptions Three categories of errors: Syntax errors Runtime errors Logic errors Syntax errors: rules of the language have not been followed. Runtime error:
CS 106 Introduction to Computer Science I 09 / 14 / 2007 Instructor: Michael Eckmann.
Copyright 2008 by Pearson Education Building Java Programs Chapter 6 Lecture 6-1: File Input with Scanner reading: , 5.3 self-check: Ch. 6 #1-6.
Loops Repeat after me …. Loops A loop is a control structure in which a statement or set of statements execute repeatedly How many times the statements.
IC211 Lecture 8 I/O: Command Line And JOptionPane.
School of Computing Science CMT1000 Ed Currie © Middlesex University Lecture 4: 1 CMT1000: Introduction to Programming Ed Currie Lecture 5a: Input and.
Relational Operators Control structures Decisions using “if” statements  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 6: File Processing.
1 Scanner objects. 2 Interactive programs We have written programs that print console output. It is also possible to read input from the console.  The.
Computer Programming Lab(5).
JOptionPane class. Dialog Boxes A dialog box is a small graphical window that displays a message to the user or requests input. A variety of dialog boxes.
Warm-Up: Monday, March 3 List all devices you can think of that can be used to input information into the computer.
From BlueJ to NetBeans SWC 2.semester.
Conditional If Week 3. Lecture outcomes Boolean operators – == (equal ) – OR (||) – AND (&&) If statements User input vs command line arguments.
John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:
John Hurley Cal State LA CS 201 Lecture 4. If If statements do just what you expect test whether a condition is true and if so, execute some statements.
OOP (Java): Simple/ OOP (Java) Objectives – –give some simple examples of Java applications and one applet 2. Simple Java Programs Semester.
Lecture 2: Classes and Objects, using Scanner and String.
Jaeki Song ISQS6337 JAVA Lecture 03 Introduction to Java -The First Java Application-
John Hurley Cal State LA CS 201 Lecture 5. 2 Loops A loop performs a set of instructions repeatedly as long as some condition is met while (x != 0) {
Input/Output in Java. Output To output to the command line, we use either System.out.print () or System.out.println() or System.out.printf() Examples.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
Lecture 3 Decisions (Conditionals). One of the essential features of computer programs is their ability to make decisions. Like a train that changes tracks.
CS 106 Introduction to Computer Science I 01 / 31 / 2007 Instructor: Michael Eckmann.
1 BUILDING JAVA PROGRAMS CHAPTER 6 DETAILS OF TOKEN-BASED PROCESSING.
Programming Fundamentals 2: Simple/ F II Objectives – –give some simple examples of Java applications and one applet 2. Simple Java.
Dialog Boxes.
FUNDAMENTALS 2 CHAPTER 2. OPERATORS  Operators are special symbols used for:  mathematical functions  assignment statements  logical comparisons 
CHAPTER 5 GC 101 Input & Output 1. INTERACTIVE PROGRAMS  We have written programs that print console output, but it is also possible to read input from.
Introduction Chapter 1 8/31 & 9/1 Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010.
Introduction to Computing Concepts Note Set 15. JOptionPane.showMessageDialog Message Dialog Allows you to give a brief message to the user Can be used.
Reading input from the console input. Java's console input The console is the terminal window that is running the Java program I.e., that's the terminal.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 1 Introduction to Computers, Programs,
1 Class Chapter Objectives Use a while loop to repeat a series of statements Get data from user through an input dialog box Add error checking.
Computer Programming1 Computer Science 1 Computer Programming.
Casting, Wrapper Classes, Static Methods, JOptionPane Class.
Computer Programming Lab 9. Exercise 1 Source Code package excercise1; import java.util.Scanner; public class Excercise1 { public static void main(String[]
import java.util.Scanner; class myCode { public static void main(String[] args) { Scanner input= new Scanner(System.in); int num1; System.out.println(“Enter.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:
AP Java 10/1/2015. public class Rolling { public static void main( String [] args) public static void main( String [] args) { int roll; int roll; for.
John Hurley Spring 2011 Cal State LA CS 201 Lecture 5:
CompSci 230 S Programming Techniques
INTERMEDIATE PROGRAMMING USING JAVA
OBJECT ORIENTED PROGRAMMING I LECTURE 10 GEORGE KOUTSOGIANNAKIS
Intro to ETEC Java.
Exercise 1- I/O Write a Java program to input a value for mile and convert it to kilogram. 1 mile = 1.6 kg. import java.util.Scanner; public class MileToKg.
John Hurley CS201 Cal State LA
OBJECT ORIENTED PROGRAMMING I LECTURE 7 GEORGE KOUTSOGIANNAKIS
Elementary Programming
John Hurley Cal State LA
Objectives You should be able to describe: Interactive Keyboard Input
AP Java 10/4/2016.
Lecture 3 Lists Linear and Binary Search C Structs .jar files
Computer Programming Methodology Input and While Loop
OBJECT ORIENTED PROGRAMMING I LECTURE 7 GEORGE KOUTSOGIANNAKIS
AP Java 10/4/2016.
Building Java Programs
Introduction to Java Brief history of Java Sample Java Program
Object Oriented Programming
Indefinite loop variations
JOptionPane class.
F II 2. Simple Java Programs Objectives
Random Numbers while loop
Chapter 2: Java Fundamentals cont’d
Validation We have covered one way to get user input, using Scanner to get it from the console We will soon cover at least one additional way to get.
Presentation transcript:

CS 201 Lecture 7: John Hurley Summer 2012 Cal State LA

Programming Errors Syntax Errors Runtime Errors Logic Errors Incorrect Java. An IDE will warn you about these, but at a command line, they would be detected by the compiler; also called "compiler errors" Runtime Errors Cause the program to abort; in CS202 you will learn how to manage many of these to avoid program crashes. Logic Errors Produce incorrect results 2

Syntax Error public class Errors{ public static void main(String[] args){ int i = 1 System.out.println(i); } 3

Runtime Error public class Errors{ public static void main(String[] args){ int y = 10; for(int x = 0; x <=10; x++){ y -= 1; System.out.println(10 / y); } 4

Logic Error public class PowerError{ public static void main(String[] args){ int answer = 1; for(int power = 0; power <= 10; power++){ answer = answer * 2; System.out.println("2 ^ " + power + " = " + answer); } 5

Test Your Work It is easy to test our programs in which there is only one sequence the computer can follow: public class Power{ public static void main(String[] args){ int answer = 1; for(int power = 0; power <= 10; power++){ System.out.println("2 ^ " + power + " = " + answer); answer = answer * 2; }

Test Your Work At this point, we are writing programs that take user input Users are human beings The next slide shows a statistically representative sample of human beings

Test Your Work Program execution becomes more complex when unpredictable human beings intervene Make sure to test thoroughly The success rate of untested programs is close to 0 We have it easy. Testing involves saving, compiling, and running on a machine that is at our fingertips; it hasn’t always been that way.

Dialog Boxes GUI construction is taught in CS202, but we will cover a few GUI rudiments in 201 The first is the JOptionPane class, which provides pop-up I/O boxes of several kinds Need to include this at the very top of your class: import javax.swing.JOptionPane; JOptionPane.showMessageDialog() displays a dialog box with text you specify

Dialog Boxes import javax.swing.JOptionPane; public class DialogBox{ public static void main(String[] args){ for(int i = 0; i < 4; i++) { JOptionPane.showMessageDialog(null, "This is number " + i); }

Dialog Boxes JOptionPane.showInputDialog() shows a dialog box that can take input The input is a String We will learn soon how to parse from String to other types

Dialog Boxes import javax.swing.JOptionPane; public class InputBox{ public static void main(String[] args){ String input = JOptionPane.showInputDialog(null, "Please enter some input "); JOptionPane.showMessageDialog(null, "You entered: \"" + input + "\""); String input2 = input.concat(" " + JOptionPane.showInputDialog(null, "Please enter some more input ")); JOptionPane.showMessageDialog(null, "You entered: \"" + input2 + "\""); }

Casting Strings to Numeric Types Recall that input from JOptionPane.showInputDialog is a String Cast to integer: Integer.parseInt(intString); Example: String input = int age = Integer.parseInt(JOptionPane. showInputDialog(null, “Please enter your age”); Cast to double: Double.parseDouble(doubleString);  

Casting to Numeric Types Note the capitalization in the method names. Double and Integer are not quite the same as double and integer. You’ll understand when you are a little older…

Parsing to Integer import javax.swing.JOptionPane; public class NumericCastDemo{ public static void main(String[] args){ int age = Integer.parseInt(JOptionPane.showInputDialog(null, "Please enter your age")); if(age < 30) JOptionPane.showMessageDialog(null, age + " is pretty young."); else if(age > 100) JOptionPane.showMessageDialog(null, "really?"); else JOptionPane.showMessageDialog(null, "That's OK. Methuseleh lived to be " + (270 - age) + " years older than you are now."); } // end main() } // end class

Parsing to Double import javax.swing.JOptionPane; public class NumericCastDemo{ public static void main(String[] args){ double age = Double.parseDouble(JOptionPane.showInputDialog(null, "Please enter your age")); if(age < 30) JOptionPane.showMessageDialog(null, age + " is pretty young."); else if(age > 100) JOptionPane.showMessageDialog(null, "really?"); else JOptionPane.showMessageDialog(null, "That's OK. Methuseleh lived to be " + (270 / age) + " times as old as you are now."); } // end main() } // end class

Imports We have already discussed javax.swing.JOptionPane methods to show input and message dialogs These required the following line at the top of the class: Import javax.swing.JOptionPane; If you omit this line, you will get an error message like this: SwitchDemo.java: 7: cannot find symbol Symbol:variable JOptionPane

Imports Java classes are organized in packages Late in this class or early in CS202 you will start using packages for multiple classes javax.swing is a package of GUI-related classes that is included with all distributions of Java JOptionPane is a class within this package JOptionPane.showMessageDialog() and JOptionPane.showInputDialog are methods of the class

Imports Including a package in your program adds a small cost, slowing down the compiler as it looks through the imported package Thus, things like javax.swing are not included automatically; you must specify that you need them You will eventually be importing your own packages, too. Don’t leave unused imports in your code

Validating Data Type We have already discussed how to make sure that numeric input from Scanner is within a desired range int age; do { System.out.println("How old are you?"); age = sc.nextInt(); } while (age < 0 || age > 100);

Validating Scanner Input So far, our programs have crashed if casts to numeric types failed: Try this with input “two point five”: import java.util.Scanner; public class ReadDouble2 { public static void main(String[] args) { Scanner input = new Scanner(System.in); Double stuff = 0.0; do { System.out.print("Input a double. Enter 0 to quit:"); stuff = input.nextDouble(); System.out.println("\nYou entered: " + stuff); } while (stuff != 0.0); }

Validating Scanner Input Here is the simplest way to validate Scanner input for data type (that is, to make sure you get input that can be cast to double, integer, etc.) Scanner has hasNext…() methods that see if there is a parseable token hasNextInt() hasNextDouble() hasNextBoolean() Also need nextLine() to skip over bad input

Validating Scanner Input Try this one with input “nine.three”, then with input “nine point three: import java.util.Scanner; public class ReadDouble3 { public static void main(String[] args) { Scanner input = new Scanner(System.in); Double inpDouble = 10.0; // bad code ahead!! do { System.out.print("Input a double. Enter 0 to quit:"); if(input.hasNextDouble()){ inpDouble = input.nextDouble(); System.out.println("\nYou entered: " + inpDouble); } else input.next(); } while (inpDouble != 0.0);

Validating Scanner Input In order to get good output, we need to arrange things in a slightly more complex way: Scanner sc = new Scanner(System.in); int x; String badInputString = null; System.out.println("Enter an integer"); while (!sc.hasNextInt()) { badInputString = sc.nextLine(); System.out.println(badInputString + " isn't an integer! Please try again."); } x = sc.nextInt(); System.out.println(x);

Validating Both Type and Value int value = 0; String badInputString = null; do { System.out.println("Enter an integer greater than 100"); while (!(sc.hasNextInt())) { badInputString = sc.nextLine(); System.out.println(badInputString + " isn't an integer! Please try again."); } value = sc.nextInt(); sc.nextLine(); // throw awqay linefeed } while (value <= 100); System.out.println(value);

Documentation From Oracle When you need a reference source for something like Scanner, look it up in Oracle’s excellent online documentation Example: Google +Java +Scanner Follow the link to http://doc.java.sun.com/DocWeb/api/java.util.Scanner