Lecture 9: Bits and Pieces, Part 2 Tami Meredith.

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

8-May-15 Additional control structures. 2 The if-else statement The if-else statement chooses which of two statements to execute The if-else statement.
 2005 Pearson Education, Inc. All rights reserved Introduction.
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
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.
Introduction to Computers and Programming Lecture 4: Mathematical Operators New York University.
16-Jun-15 Additional control structures. 2 The if-else statement The if-else statement chooses which of two statements to execute The if-else statement.
Conditions What if?. Flow of Control The order of statement execution is called the flow of control Unless specified otherwise, the order of statement.
C. About the Crash Course Cover sufficient C for simple programs: variables and statements control functions arrays and strings pointers Slides and captured.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
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;
CSM-Java Programming-I Spring,2005 Control Flow Lesson - 3.
Chapter 5 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved2/33 Conditionals and Loops Now we will examine programming statements.
CIS3931 – Intro to JAVA Lecture Note Set 3 19-May-05.
Week #2 Java Programming. Enable Line Numbering in Eclipse Open Eclipse, then go to: Window -> Preferences -> General -> Editors -> Text Editors -> Check.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Conditional If Week 3. Lecture outcomes Boolean operators – == (equal ) – OR (||) – AND (&&) If statements User input vs command line arguments.
Week 2 - Monday.  What did we talk about last time?  Software development  Lab 1.
Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements.
Programming Fundamentals. Today’s lecture Decisions If else …… Switch Conditional Operators Logical Operators.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
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.
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
Compound Statements If you want to do more than one statement if an IF- else case, you can form a block of statements, or compound statement, by enclosing.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Warm-Up: Monday, March 24 List as many commands in Java as you can remember (at least 10)
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
Week 3 - Wednesday.  What did we talk about last time?  Other C features  sizeof, const  ASCII table  printf() format strings  Bitwise operations.
More Selection Executing Statements Selectively Chap. 7 (Read § & Part of Picture: Boolean Logic and Digital Design) 1.
Introduction to Java Java Translation Program Structure
Chapter 5: Control Structures II
1-Dec-15 Additional control structures. 2 The if-else statement The if-else statement chooses which of two statements to execute The if-else statement.
Control Structures - Selections - Repetitions/iterations (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
Lecture 8: Bits and Pieces Tami Meredith. Roadmap Today's lecture has a bit of everything. Going back over previous chapters and pulling out little bits.
Lecture 6: Midterm Review Tami Meredith. Programming Process How do we fill in the yellow box? Text Editor Compiler (javac) Interpreter (JVM: java) User.
Lecture 2: 1226 Review Tami Meredith. Programming Process How do we fill in the yellow box? Text Editor Compiler (javac) Interpreter (JVM: java) User.
Lecture 12: Final Review Tami Meredith. Programming Requires 1. Identification of the problem Understanding it, identifying correct solutions 2. Solving.
1 Printing in Python Every program needs to do some output This is usually to the screen (shell window) Later we’ll see graphics windows and external files.
Lecture 4: Looping Tami Meredith. Back to Basics... Programming requires: 1. Identification of the problem. 2. Solving the problem: A. Selecting the data.
Control statements Mostafa Abdallah
Lecture 2: 1226 Review II Tami Meredith. Programming Process How do we fill in the yellow box? Text Editor Compiler (javac) Interpreter (JVM: java) User.
© 2007 Pearson Addison-Wesley. All rights reserved2-1 Character Strings A string of characters can be represented as a string literal by putting double.
More Selection Executing Statements Selectively Chap. 7 (Read § & Part of Picture: Boolean Logic and Digital Design) 1.
CS 106 Introduction to Computer Science I 09 / 10 / 2007 Instructor: Michael Eckmann.
Lecture 5: Methods Tami Meredith. Roadmap The new material this week is predominantly from Chapter 5 (and Section 6.2 on static ) You should try and read.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Midterm Review Tami Meredith. Primitive Data Types byte, short, int, long Values without a decimal point,..., -1, 0, 1, 2,... float, double Values with.
Session 2 Operators, Decisions and Loops. Objectives Operators Casting data Decision marking structures Loops break, continue, return.
Control Statements: Part1  if, if…else, switch 1.
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.
Chapter 2: Data and Expressions. Variable Declaration In Java when you declare a variable, you must also declare the type of information it will hold.
Lecture 2 D&D Chapter 2 & Intro to Eclipse IDE Date.
Chapter 2 Basic Computation
Week 3 - Friday CS222.
Introduction to Computer Science / Procedural – 67130
Decisions Chapter 4.
Yanal Alahmad Java Workshop Yanal Alahmad
Chapter 5: Control Structures II
Multiple variables can be created in one declaration
Chapter 2 Basic Computation
Arithmetic operations, decisions and looping
CSS 161 Fundamentals of Computing Introduction to Computers & Java
MSIS 655 Advanced Business Applications Programming
Homework Finishing Chapter 2 of K&R. We will go through Chapter 3 very quickly. Not a lot is new. Questions?
Unit 3: Variables in Java
Problem 1 Given n, calculate 2n
Presentation transcript:

Lecture 9: Bits and Pieces, Part 2 Tami Meredith

Roadmap A brief self-evaluation exercise Today's lecture has a bit of everything Continuation of last class things we've skipped things that aren't critical but useful introductions to things you don't really need to know, but that you should be aware that they exist Even more exercises

Self Evaluation Here is some Java code: Scanner scn = new Scanner(System.in); int number = scn.nextInt(); Write a piece of Java code that prints, to the screen, " The ultimate answer " if number is equal to 42

Part 2 if (number == 42) { System.out.println("The ultimate answer"); } Now, extend this code so that it also prints " Y2K " if number equals 2000 and " Just a boring number " if it equals anything else.

Part 3 if (number == 42) { System.out.println("The ultimate answer"); } else if (number == 2000) { System.out.println("Y2K"); } else { System.out.println("Just a boring number"); } Write a piece of java code that prints your name to the screen 13 times

Part 4 for (int i = 1; i <= 13; i++) { System.out.println("Tami Meredith"); } Now, modify this code to number each line from 1 to 13, e.g.: 1. Tami Meredith 2. Tami Meredith... etc...

Part 5 for (int i = 1; i <= 13; i++) { System.out.println(i + ". Tami Meredith"); } Now, modify this code again so that you do the entire task 3 times. That is, it will print your name 13 times (numbered 1 to 13) and then it will do it again, starting at 1, and then a third time, also starting at 1. E.g., 1. Tami Meredith... etc Tami Meredith 1. Tami Meredith... etc Tami Meredith 1. Tami Meredith... etc Tami Meredith

Part 6 for (int j = 1; j <= 3; j++) { for (int i = 1; i <= 13; i++) { System.out.println(i + ". Tami Meredith"); } Write a method that takes a String as its parameter and returns the first character of the string. Do not worry about dealing with an empty string.

Part 6 public static char firstLetter (String s) { return (s.charAt(0)); } Here is some Java code: Scanner scn = new Scanner(System.in); int n1 = scn.nextInt(); int n2 = scn.nextInt(); Write a piece of Java code that swaps n1 and n2 if n1 is greater than n2.

Solution if (n1 > n2) { int temp = n1; n1 = n2; n2 = temp; }

Compound Assignment x += 1; is the same as x = x + 1; y *= x; is the same as y = y * x; Format: var op= value; is the same as var = var op value;

Conditional Expressions Format: (test) ? true-value : false-value Meaning: if test is true use true-value else use false-value Examples diff = (x > y) ? x-y : y-x; System.out.println((x>y)?(x-y):(y-x)); max = (x > y) ? x : y; return((n == 0) ? 0 : sum/n);

Stuff you won't use Shifts: byte x = 9; // x = ; x = x << 2; // x = ; x = x >> 1; // x = ; Bitwise Operations: & is bitwise and, not the same as && | is bitwise or, not the same as || ^ is bitwise complement, not the same as ! Hex constants are prefixed with 0x int x = 0x10; // x = hexidecimal 10 = 16;

Short-Circuit Evaluation Recall: x && y is true when both x and y are true If x is false, y doesn't matter To save effort, y is never examined if x is false Recall: x || y is true if x is true or y is true If x is true, y doesn't matter To save effort, y is never examined if x is true We call this behaviour short-circuit evaluation

ASCII Every character has a value We store the value, not the character Characters are just numbers! We can use the ASCII table to find the value of any character

Exercise Write a method called isUpper that takes a character as its parameter and returns true if the character is upper case and false otherwise.

Solutions public static boolean isUpper (char c) { if (('A' <= c) && (c <= 'Z')) { return (true); } return (false); } // end isUpper() public static boolean isUpper (char c) { return (('A'<=c) && (c<='Z') ? true : false); } // end isUpper()

Switch Statement Provides an alternative way to write complex if-else sets of statements Choice must be based on a single value, not a range of values For example, consider that we want to keep track of playing cards, so we decide: hearts = 0, clubs = 1, spades = 2, diamonds = 3 We could print out then names for each value in two ways (next slide)

Example if (suite == 0) { System.out.print("Hearts"); } else if (suite == 1) { System.out.print("Clubs"); } else if (suite == 2) { System.out.print("Spades"); } else if (suite == 3) { System.out.print("Diamonds"); } else { System.out.print("Error"); } switch (suite) { case 0: System.out.print("Hearts"); break; case 1: System.out.print("Clubs"); break; case 2: System.out.print("Spades"); break; case 3: System.out.print("Diamonds"); break; default: System.out.print("Error"); }

Format switch ( expression ) { case value1 :... actions... break; case value2 :... actions... break; default:... actions... } The expression must be something that produces an integer (of any type), character, or string If no break occurs, the next case is ignored and its actions are carried out! Forgetting the break is a major cause of errors when using switch

break break is used in switch statements to end a case break is also used in loops to exit a loop e.g. for (int x = start; x < end; x++) { if (x == 0) { System.out.println("done"); break; } System.out.print(x + ", "); }

More about break When we have nested loops, break only exits the inner-most loop that the break is inside of There is no way to exit multiple loops using break Control jumps to the statement immediately following the loop The use of break can be avoided by having more complicated loop tests – it is not needed, but it often makes code much clearer and simpler, and easier to understand

continue Sometimes we want to skip the body of a loop, but not exit the loop continue causes a jump to the test (do/while) or step (for) of a loop – i.e., jump back to the top continue does not exit a loop e.g. for (int x = start; x < end; x++) { if (x == 0) { continue; } System.out.print("1/" + x + "=" + (1/x)); }

Exercise Write code to create an array called Jun e Note: I am asking for code, NOT a program, NOT a method, just a few lines of Java! Array element zero should hold "Error" Array element one should hold "Saturday" Every index after that (up to and including 30) should hold the appropriate day of the week

Solution 1 String[] June = new String[31]; June[0] = "Error"; for (int i = 1; i < 31; i++) { if ((i % 7) == 0) June[i] = "Friday"; else if ((i % 7) == 1) June[i] = "Saturday"; else if ((i % 7) == 2) June[i] = "Sunday"; else if ((i % 7) == 3) June[i] = "Monday"; else if ((i % 7) == 4) June[i] = "Tuesday"; else if ((i % 7) == 5) June[i] = "Wednesday"; else June[i] = "Thursday"; }

Solution 2 String[] June = new String[31]; June[0] = "Error"; for (int i = 1; i < 31; i++) { switch (i % 7) { case 0: June[i] = "Friday"; break; case 1: June[i] = "Saturday"; break; case 2: June[i] = "Sunday"; break; case 3: June[i] = "Monday"; break; case 4: June[i] = "Tuesday"; break; case 5: June[i] = "Wednesday"; break; case 6: June[i] = "Thursday"; break; }

Solution 3 String[] June = new String[31]; June[0] = "Error"; int[] week = {"Friday", "Saturday", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday"}; for (int i = 1; i < 31; i++) { June[i] = week[i%7]; }

printf printf is the most powerful (and complicated) output function It was originally in the C programming language and was added to Java because a lot of C programmers wanted it! Described on page 101 – 102 Gives really good control of the output and its format

printf Formats printf ( format-string,... values... ) There must be one value for every specifier in the format string format specifiers begin with a % and are placed in the format string E.g. printf("Hello %s!", name); In this example %s means, put a string here, and name is used to provide the string There might not be any values! E.g., printf("Hello!"); is the same as print("Hello");

Format Specifiers %c – a character %s – a string %d – an integer %f – a floating point number We can modify the values to have a minimum and a maximum size E.g., %5d – an integer with 5 digits (spaces added if needed) See:

Escaped Characters Sometimes we want to remove or add meaning to characters in a string (Figure 2.6) To do this we use the escape character '\' to escape the normal meaning of the next character \" – double quote, don't end the string \' – single quote \\ - just a backslash, not an escape \n – newline (go to beginning of next line) \t – tab, expanded using system default \r – carriage return (same as newline... maybe)

The Math class There are many common mathematical operations that are provided for you These methods are static methods in the Math class Math is automatically provided, no import is needed They are called by preceding the name of the method with the class name E.g., double root = Math.sqrt(30.0); See Figure 6.3 for a listing of some methods provided

Math Methods pow(x,y); returns x y abs(x); returns the absolute value of x random(); returns a pseudo-random number in the range 0 ≤ x < 1 sqrt(x); returns the square root of x Others exist as well as variants of some (e.g., random ) They use double, not float

Exercise Write a program that obtains a line of user input and prints out all the capital letters in that line. E.g.: Enter a line of text: Hi there SleEpY HeAD! HSEYHAD

Solution import java.util.*; public class capitals { public static void main (String[] args) { Scanner kbd = new Scanner(System.in); System.out.print("Enter a line of text: "); String input = kbd.nextLine(); char c; for (int index = 0; index < input.length(); index++) { c = input.charAt(index); if (('A' <= c) && (c <= 'Z')) { System.out.print(c); } System.out.println(""); } // end main() } // end class capitals

Keep Calm! We're getting there

To Do Go to the lab and complete Assignment 8 Read and re-read Chapters 1-4, and 7 – know this material VERY well Keep working on Chapters 5, 6 - most of Chapter 6 we have not covered, nor the part of Chapter 5 on objects and classes Practice, Practice, Practice! Do more practice! Did I mention it would help to practice?