John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:

Slides:



Advertisements
Similar presentations
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Advertisements

1 Control Structures (and user input). 2 Flow of Control The order statements are executed is called flow of control By default, statements in a method.
 2002 Prentice Hall. All rights reserved. 1 Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures 4.5 The if Selection Structure.
Loops – While Loop Repetition Statements While Reading for this Lecture, L&L, 5.5.
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
Introduction to Computers and Programming Lecture 8: More Loops New York University.
Loop variations do-while and for loops. Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop.
Loops – While, Do, For Repetition Statements Introduction to Arrays
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.
FIT Objectives By the end of this lecture, students should: understand iteration statements understand the differences of for and while understand.
1 Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures 4.5 if Single-Selection Statement 4.6 if else Selection Statement 4.7 while.
Relational Operators Control structures Decisions using “if” statements  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course.
 2003 Prentice Hall, Inc. All rights reserved. 1 Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures 4.5 if Single-Selection.
 2003 Prentice Hall, Inc. All rights reserved. 1 Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures 4.5 if Single-Selection.
1 The First Step Learning objectives write Java programs that display text on the screen. distinguish between the eight built-in scalar types of Java;
Writing algorithms using the while-statement. Previously discussed Syntax of while-statement:
Iteration. Adding CDs to Vic Stack In many of the programs you write, you would like to have a CD on the stack before the program runs. To do this, you.
Java Programming: From the Ground Up
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.
Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester,
Lecture 2: Classes and Objects, using Scanner and String.
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved John Hurley Cal State LA CS 201.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
1 Fencepost loops “How do you build a fence?”. 2 The fencepost problem Problem: Write a class named PrintNumbers that reads in an integer called max and.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 3.
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
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) {
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.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Logic Our programs will have to make decisions in terms of what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Control Structures: Part 1.
1 Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures 4.5 The if Selection Structure 4.6 The if / else Selection Structure 4.7.
Chapter 4: Control Structures II
 2003 Prentice Hall, Inc. All rights reserved. 1 Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures 4.5 if Single-Selection.
Chapter 5: Control Structures II
FUNDAMENTALS 2 CHAPTER 2. OPERATORS  Operators are special symbols used for:  mathematical functions  assignment statements  logical comparisons 
Java iteration statements ● Iteration statements are statements which appear in the source code only once, but it execute many times. ● Such kind of statements.
Introduction to Computing Concepts Note Set 15. JOptionPane.showMessageDialog Message Dialog Allows you to give a brief message to the user Can be used.
Object Oriented Programming (OOP) LAB # 1 TA. Maram & TA. Mubaraka TA. Kholood & TA. Aamal.
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.
Boolean expressions, part 1: Compare operators. Compare operators Compare operators compare 2 numerical values and return a Boolean (logical) value A.
 2003 Prentice Hall, Inc. All rights reserved. 1 Will not cover 4.14, Thinking About Objects: Identifying Class Attributes Chapter 4 - Control Structures.
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.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
John Hurley Spring 2011 Cal State LA CS 201 Lecture 5:
CS 106 Introduction to Computer Science I 02 / 15 / 2008 Instructor: Michael Eckmann.
Lecture 11 CS201.
OBJECT ORIENTED PROGRAMMING I LECTURE 10 GEORGE KOUTSOGIANNAKIS
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.
CS 201 Lecture 7: John Hurley Summer 2012 Cal State LA.
John Hurley CS201 Cal State LA
Java Course Review.
John Hurley Cal State LA
Chapter 5: Control Structures II
Computer Programming Methodology Input and While Loop
Chapter 4 – Control Structures Part 1
Chapter 5: Control Structures II
Python programming exercise
Building Java Programs
Week 4 Lecture-2 Chapter 6 (Methods).
Chapter 4 - Control Structures: Part 1
F II 2. Simple Java Programs Objectives
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:

John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:

Nested Loops One loop may be inside another one Inner loop will execute its full run for every iteration of the outer loop Inner loop may use variables controlled by the outer loop How many times does the statement in bold execute? public class NestedLoopDemo{ public static void main(String[] args){ for(int a = 1; a <= 10; a++){ for(int b = 1; b <= 10; b++){ System.out.printf("\nvariable a: %d\t variable b: %d", a, b); } How would you do a multiplication table?

Nested Loops Consider a case in which, for each iteration of the outer loop, the inner loop executes the same number of times as the outer loop: public class NestedLoopDemo2{ public static void main(String[] args){ int count = 0; int max = 10; for(int a = 1; a <= max; a++){ for(int b = 1; b <= max; b++){ System.out.printf("\nvariable a: %d\t variable b: %d", a, b); count++; } System.out.println("\ntotal number of prints: " + count); } At the end of the method, count = max 2

Nested Loops What about this one? public class NestedLoopDemo3{ public static void main(String[] args){ int count = 0; int max = 5; for(int a = 0; a < max; a++){ for(int b = 0; b < a; b++){ System.out.printf("\nvariable a: %d\t variable b: %d", a, b); count++; } System.out.println("\ntotal number of prints: " + count); } At the end of the method, count = … + (max – 1)

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

Command Line Input There are several ways to get input from a command line In production, you will usually write programs that use GUIs, not command line I/O In school most programming classes focus on functionality, not user interface, so you need to know how to use command line I/O

Command Line Input The simplest command line input class is Scanner import java.util.Scanner; Scanner has a variety of methods to get input of different data types

Scanner Input Methods We describe methods using in this format: Class.method() If there are any parameters, their type goes inside the parentheses You have already seen System.out.println(String) JOptionPane.showMessageDialog(null, message) You will often replace the class name with the name of an instance of the class: Scanner input = new Scanner(System.in); … stuff deleted… name = input.next(); In the example above, input is an instance of Scanner. We set up a Scanner and called it input!

Scanner Input Methods Scanner.next() reads the next parseable string Scanner.nextLine() reads up to the next line break and puts the result in a String Scanner.nextDouble() reads the next parseable string and tries to convert it to a Double double d = Scanner.nextDouble(); There are equivalent methods for nextInteger(), nextBoolean(), etc.

Scanner.next Example import java.util.Scanner; public class Candyman { public static void main(String[] args) { Scanner input = new Scanner(System.in); String name = null; int candyCount = 0; do { System.out.println("Guess my name:"); name = input.next(); if(name.equals("Candyman")) candyCount += 1; } while (candyCount < 3); System.out.println("You called the Candyman three times, fool! Now he will eat you! Be more careful next time!"); }

Scanner.nextDouble Example import java.util.Scanner; public class ReadDouble { public static void main(String[] args) { Scanner input = new Scanner(System.in); Double stuff = 0.0; do { System.out.print("Input a double:"); stuff = input.nextDouble(); System.out.println("\nYou entered: " + stuff); } while (stuff != 0.0); }

Validating Scanner Input We have already discussed how to make sure that numeric input from Scanner or JOptionPane is within a desired range double oldGPA = 0; do{ oldGPA = Double.parseDouble(JOptionPane.showInputDialog(null, "Please enter your current GPA")); }while(oldGPA 4);

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 next() 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 = 0.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, wee need to arrange things in a slightly more complex way: import java.util.Scanner; public class ReadInt{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); System.out.print("Enter number 1: "); while (!sc.hasNextInt()) sc.next(); int num1 = sc.nextInt(); int num2; System.out.print("Enter number 2: "); do { while (!sc.hasNextInt()) sc.next(); num2 = sc.nextInt(); } while (num2 < num1); System.out.println(num1 + " " + num2); }

Documentation From Oracle Java was originally developed by Sun Microsystems and was closed-source but free for many years Java is now open-source Anyone is free to use it or to write compilers, virtual machines, etc. that implement it Oracle bought Sun a couple of years ago and now is the champion of Java In reality, except in some specialized areas like Android development, everyone uses Oracle’s implementations

Documentation From Oracle When you need to use something like Scanner, look it up in Oracle’s excellent online documentation Example: Google +Java +Scanner Follow the link to

Pseudocode 21 Algorithms are often described with pseudocode Pseudo means “almost” or “fake” Pseudocode uses various constructs that are common to many programming languages Pseudocode is a way to abstract algorithms from the details of particular programming languages Pseudocode is only pseudostandardized. You will see many different notations.

Pseudocode 22 function factorial is: input: integer n such that n >= 0 output: [n × (n-1) × (n-2) × … × 1] Iterative algorithm 1. create new variable called running_total with a value of 1 2. begin loop 1. if n is 0, exit loop 2. set running_total to (running_total × n) 3. decrement n 4. repeat loop 3. return running_total end factorial

Pseudocode 23 Here is a different pseudocode format: procedure bizzbuzz for i := 1 to 100 do set print_number to true; if i is divisible by 3 then print "Bizz"; set print_number to false; if i is divisible by 5 then print "Buzz"; set print_number to false; if print_number, print i; print a newline; end

Pseudocode 24 Here is yet another format, this one more abstract: initialize passes to zero initialize failures to zero set minimum passing score to 70 set number of students to 10 for each student get the student's exam result from input if the student's score is greater than or equal to the passing score add one to passes else add one to failures print the number of passes print the number of failures if at least 70% of students passed print "The university is succeeding! Raise tuition!" else print "The university needs more resources! Raise tuition!"