Presentation is loading. Please wait.

Presentation is loading. Please wait.

Strings, conditional statements, Math

Similar presentations


Presentation on theme: "Strings, conditional statements, Math"— Presentation transcript:

1 Strings, conditional statements, Math
CSC 211 Java I Strings, conditional statements, Math

2 Today’s plan Administrivia More on algorithms Conditionals
Q/A on assignment Review of quarter More on algorithms Conditionals If If – else Math class (API) Math.Random()

3 Topic review Variables Arithmetic operators Output Input
Basic algorithms Using predefined classes (Square, Scanner, String) Output System.out.print System.out.println Input Scanner Variables Identifiers Primitive data types Arithmetic operators Precedence String concatenation Parameter passing API

4 Today’s plan Administrivia More on algorithms Conditionals
Q/A on assignment Review More on algorithms Conditionals If If – else Math class (API) Math.Random()

5 Guessing Game The game Do Part 1.1 of Lab 3
The machine chooses an integer between 1 and 10 The machine asks the user to enter a guess of what number was chosen The machine then tells the user whether he/she guessed correctly Do Part 1.1 of Lab 3

6 Are you with me? Copy and paste your algorithm here (Text)

7 Pick up some good habits early
Brain, pen, and paper Java and compiler Understand the problem and work out scenarios Break down the problem and the solution into smaller chunks Start by writing the JEnglish version of the program Think of test cases you can run to validate your solution Start by writing the overall structure of the program Most of it should be just comments of what will come Write only a few lines of code at a time Test each small step!!! Make sure you have the basic input/output working before coding the rest of the logic Test every new piece of code you add

8 Are you with me? Which of the following is the correct sequence for a complete program? Sequence A: Import statement Class declaration Main method Sequence B: Sequence C:

9 Guessing Game Do Parts 1.2 and 1.3 of Lab 3 Modify the algorithm
Create the class and main structure Make sure you can store the computer’s number and print it back for the user Make sure you can get a guess from the user and, for now, simply print it back to the screen We will implement the comparison later

10 Today’s plan Administrivia More on algorithms Conditionals
Q/A on assignment Review More on algorithms Conditionals If If – else Math class (API) Math.Random()

11 Guessing Game Computer generates a number (N) Control structures:
User inputs a guess (G) Control structures: The if statement Output N and G Is N=G ? Output: Congratulations! true false Exit the program

12 Remaining program statements
The if statement condition if (condition) if_true_statements if_true_statements true { } Remaining program statements false Back to the program

13 More on if Note: There is no ; in the if line
if (condition) if_true_statements { } Back to the program Note: There is no ; in the if line The condition is in between ( and ) All statements to be executed when the condition is true are between { and } The condition (inside the parentheses) has to be an expression that evaluates to a boolean (i.e. is either true or false)

14 Are you with me? What will you see? (Text) int x = 5; if (x > 0) {
System.out.println(x + "is positive"); System.out.println("What’s next?"); } System.out.println("Moving on...");

15 Are you with me? What will you see? (Text) int x = 5; int y = -4;
x = y; if (x > 0) { System.out.println(x + "is positive"); System.out.println("What’s next?"); } System.out.println("Moving on...");

16 Are you with me? What will you see? (Text) int x = 5; int y = -4;
When trying to interpret a program, use a piece of scratch paper, do a variable trace to keep track of the value of the variables as they are changed. The unexpected output from the division x=x/z will be explained shortly. int y = -4; x = y; int z = -10; x = x/z; if (x > 0) { System.out.println(x + "is positive"); System.out.println("What’s next?"); } System.out.println("Moving on...");

17 boolean variables A boolean is a Java primitive data type
It has only 2 possible values: true / false int x = 10; boolean flag = true; System.out.println ("value of flag is: " + flag); flag = (x <= 8); System.out.println("Value of flag is: " + flag); true false

18 Are you with me? What will you see on the screen? (Ink) True False
int x = 10; boolean flag = x <= 8; System.out.println("The value of flag is " + flag);

19 Digression: Remember that the assignment operator is evaluated first.
We say that the assignment operator has ‘low precedence’. (More on this later in the course) This code would probably be clearer if we used parentheses: int x = 10; boolean flag = (x <= 8); System.out.println("The value of flag is " + flag);

20 Relational Operators <, <=, >, >=, == Binary operators
Take two primitive type operands i.e. You can’t compare objects using these operators! (e.g. no Strings) The result of a binary comparison will always produce a boolean result (i.e. true or false) Note that <= and >= are two-character operators

21 Equality Operators Two operators
Not equal != As before, both of these operators work with primitive operands and produce a boolean result Both are two-character operators Parentheses can be used with equality and relational operators (later)

22 Multiple comparisons (common):
Sometimes one simple comparison isn’t enough. For example: Decide if a customer qualifies for a reduced movie ticket using the following rules: Is a student OR Is a senior citizen (65 or older) if (age <=18)  not enough! if (age >= 65)  also not enough! Answer: if (age <=18 OR age >= 65)  adjust ticket cost How can we express this in code?

23 Multiple comparisons contd:
Another example: Another movie theater only gives student discounts if the customer is a student AND is 18 or less. Is a student AND Is 18 years or less if (student == true)  not enough! if (age <= 18)  also not enough! Answer: if (age <=18 AND student==true)  adjust ticket cost How can we express this in code?

24 Logical AND and logical OR
The logical AND, represented by ‘&&’: a && b is true if and only if both a and b are true, false otherwise The logical OR, represented by ‘||’: a || b is true as long as either a or b is true. a b a&&b a||b T F && and || Take 2 boolean values Return a boolean value

25 Short circuiting The two operands (comparisons) of && and || are evaluated in order (left to right) If the first operand for && is false, the second is never evaluated If the first operand for || is true, the second is never evaluated This can be very tricky if your operands change state Be careful! More later…

26 We have another tool Now you know how to implement conditionals:
Is the number entered by the user the same one chosen by the computer? Do Parts 1.4 , 1.5, and 1.6 of Lab 3

27 Go with the flow Here is one solution:
We can build the output string in two parts: core = "The machine picked … " "you picked …"; addOn = "You lose" ; // This is the default If the user guesses the right number we change: addOn = "You win" At the end we print core + addOn

28 A new guessing game The new game Do Part 2.1 of Lab 3
The machine chooses an integer between 1 and 10 The machine asks the user to enter a guess of what number was chosen The machine then tells the user whether he/she guessed correctly The machine also tells the user whether an incorrect guess is too high or too low Do Part 2.1 of Lab 3

29 Today’s plan Administrivia More on algorithms Conditionals
Q/A on assignment Review More on algorithms Conditionals If If – else Math class (API) Math.Random()

30 Remaining program statements
The if-else statement condition if (condition) if_true_statements if_false_statements false if_true_statements true { } else if_false_statements Remaining program statements Back to the program

31 Are you with me? What will you see? (Text) int x = 5; if (x > 0) {
System.out.println(x + "is positive"); } else System.out.println(x + "is negative"); System.out.println(“Moving on");

32 Are you with me? What will you see? (Text) int x = 5; int y = -4;
x = y; if (x > 0) { System.out.println(x + "is positive"); } else System.out.println(x + "is negative"); System.out.println(“Moving on");

33 Are you with me? What will you see? (Text) int x = 5; int y = -4;
x = y; int z = -10; x = x/z; if (x > 0) { System.out.println(x + "is positive"); } else System.out.println(x + "is negative"); System.out.println(“Moving on");

34 We have another tool Now you know how to implement conditionals with both true and false actions. So, modify your game: If the guess is correct, display the program information and congratulations If the guess is incorrect, determine if the guess is too high or too low and give feedback Do Part 2.2 of Lab 3

35 ARE YOU WITH ME? (Text) Paste the section of code you just worked on (part 2.2):

36 Today’s plan Administrivia More on algorithms Conditionals
Q/A on assignment Review More on algorithms Conditionals If If – else Math class (API) Math.Random()

37 No more cheating! Recall how we cheated by hard-coding the supposedly “random” number. How can we get the computer to choose a new number every time we run the program? We can have the computer generate a random number In the Java API exists a method that does exactly that! The method exists in a class called ‘Math’ The Math class has a lot of very useful methods including square roots, absolute values, random numbers, etc …

38 The Math class Where would you go to find out more about the Math class and its methods? API: static double random() Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0. Do Part 3.1 of Lab 3 Continue until you are stuck – then class discussion

39 Random integers in [1,M] To generate a random integer between 1 and M (5 in this case) we need: int answer, M = 5; answer = Math.random() ; Type casting The random number is now an integer Now the random number is in the range [0,M) Now it is a random integer in the range [1 , M+1) same as [1 , M] (int) The random method of the Math class generates a double random number in the range [0, 1) ( * M) + 1 Complete Part 3.1 of Lab 3

40 Data Conversions Java is not good at data conversion:
Yosef: 7/2 is 3.5 (in my mind I automatically convert integers  floating point) Java: 7/2 is 3 because you told me to use integers! If both operands to the division operator (/) are integers, the result is an integer (the fractional part is discarded) 14 / equals? 4 8 / equals?

41 Data Conversions Data conversions can occur in three ways:
assignment conversion arithmetic promotion casting Assignment conversion occurs when a value of one type is assigned to a variable of another Arithmetic promotion happens automatically when operators in expressions convert their operands

42 Data conversion Widening conversions are safest because they tend to go from a small data type to a larger one a short to an int an int to a double The compiler does not complain if we try to do widening conversions by assignment int myInt = 7; double myDouble; myDouble = myInt;

43 Data conversion Narrowing conversions can lose information because they go from a large data type to a smaller one an int to a short a double to an int The compiler warns us that precision might be lost if we try to perform a narrowing conversion by assignment!

44 Arithmetic promotion If either or both operands to an arithmetic operator are floating point (float or double), the result is a floating point double myDouble = 4.2; int myInteger = 2; ?? result = myDouble/myInteger; Arithmetic promotion converts myInteger to a double What if I declare result as an int?

45 A first glance at casting (imp!)
Java lets us force a narrowing conversion by using a particular operation called casting Casting can be done for primitive data types and for objects (which we will see later) To cast a primitive data type DOWN to a narrower type we use the name of the narrow type in parenthesis, directly in front of the item we need to cast (int)(myDouble/MyInt);

46 Using the new tools You can now generate random integers in any range [1,n] Now the program can stop cheating and start choosing a real guess. Do Parts 3.2, and 3.3 of Lab 3


Download ppt "Strings, conditional statements, Math"

Similar presentations


Ads by Google