Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Lecture 9: Bits and Pieces, Part 2 Tami Meredith."— Presentation transcript:

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

2 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

3 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

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

5 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

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

7 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... 13. Tami Meredith 1. Tami Meredith... etc... 13. Tami Meredith 1. Tami Meredith... etc... 13. Tami Meredith

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

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

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

11 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;

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

13 Stuff you won't use Shifts: byte x = 9; // x = 0000 1001; x = x << 2; // x = 0010 0100; x = x >> 1; // x = 0001 0010; 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;

14 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

15 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

16

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

18 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()

19 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)

20 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"); }

21 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

22 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 + ", "); }

23 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

24 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)); }

25 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

26 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"; }

27 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; }

28 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]; }

29 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

30 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");

31 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: http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax

32 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)

33 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

34 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

35 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

36 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

37 Keep Calm! We're getting there

38 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?


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

Similar presentations


Ads by Google