Think Twice Code Once The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2005 Khaleel I. Shaheen Computer Programming, I Laboratory Manual Experiment #3 Selections
Numeric Type Conversions You can always assign a value to a numeric variable whose type supports a larger range of values; thus, for instance, you can assign a long value to a float variable. You cannot, however, assign a value to a variable of a type with a smaller range unless you use type casting. Casting is an operation that converts a value of one data type into a value of another data type. Casting a type with a small range to a type with a larger range is known as widening a type. Casting a type with a large range to a type with a smaller range is known as narrowing a type. widening is called implicit casting because Java will automatically widen a type, but you must narrow a type explicitly, so narrowing is called explicit casting. Widening examples: double x = 3 * 4.5; // implicit widening, 3 is now 3.0 int i = 5; double d = i; // implicit widening, d is now 5.0 Narrowing examples: double d = 10.5; int i = (int) d; // explicit narrowing, i is now 10 As we saw, when a double value is cast into an int value, the fractional part is truncated. Casting is necessary if you are assigning a value to a variable of a smaller type range, such as assigning a double value to an int variable. byte < short < int < long < float < double Ex: What is sum after executing the following code: int sum = 0; sum += 4.5; Solution: sum += 4.5 is equivalent to sum = (int)(sum + 4.5). 2
Boolean Data Type The boolean data type declares a variable with the value either true or false. A variable that holds a Boolean value is known as a Boolean variable. The boolean data type is used to declare Boolean variables. A boolean variable can hold one of the two values: true or false. boolean ison = true; true and false are literals, just like a number such as 10. They are treated as reserved words and cannot be used as identifiers in the program. Java provides six relational operators (comparison operators), which can be used to compare two values and return a boolean value: Ex: Assuming that x = 1, show the result of the following Boolean expressions: x > 0 x < 0 x!= 0 x >= 0 x!= 1 3
if Statements An if statement is a construct that enables a program to specify alternative paths of execution. A one-way if statement executes an action if and only if the condition is true. For example: public class computec { public static void main(string[] args) { System.out.print("Enter radius: "); double radius = input.nextdouble(); if (radius >= 0) { double c = 2 * 3.14159 * radius; System.out.println("C is: " + c); The block braces can be omitted if they enclose a single statement. 4
Two-Way if-else Statements An if-else statement decides the execution path based on whether the condition is true or false. If the boolean-expression evaluates to true, the statement(s) for the true case are executed; otherwise, the statement(s) for the false case are executed. For example: public class computec { public static void main(string[] args) { System.out.print("Enter radius: "); double radius = input.nextdouble(); if (radius >= 0) { double c = 2 * 3.14159 * radius; System.out.println("C is: " + c); else { System.out.println("radius cannot be negative"); Ex: What is the output of the code? 5
Nested if and Multi-Way if-else Statements An if statement can be inside another if statement to form a nested if statement. The nested if statement can be used to implement multiple alternatives. The statement below prints a letter grade according to the score, with multiple alternatives. double score = 85; if (score >= 90.0) System.out.print("A"); else if (score >= 80.0) System.out.print("B"); else if (score >= 70.0) System.out.print("C"); else if (score >= 60.0) System.out.print("D"); else System.out.print("F"); Logical Operators Sometimes, whether a statement is executed is determined by a combination of several conditions. You can use logical operators to combine these conditions to form a compound Boolean expression. Logical operators, also known as Boolean operators, operate on Boolean values to create a new Boolean value. The logical operators!, &&,, and ^ can be used to create a compound Boolean expression. 6
Ex: Modify the previous example to ensure that the grade is between 0 and 100. If not, then output error message to the user. double score = 85; if (score < 0 score > 100) { System.out.println("Score is wrong"); else { if (score >= 90.0) System.out.print("A"); else if (score >= 80.0) System.out.print("B"); else if (score >= 70.0) System.out.print("C"); else if (score >= 60.0) System.out.print("D"); else System.out.print("F"); switch Statements A switch statement executes statements based on the value of a variable or an expression. The full syntax for the switch statement is as follows: switch (switch-expression) { case value1: statement(s)1; case value2: statement(s)2;... case valuen: statement(s)n; default: statement(s)-for-default; Notes about switch statement: The switch-expression must yield a value of char, byte, short, int, or String type and must always be enclosed in parentheses. The value1,..., and valuen must have the same data type as the value of the switchexpression. 7
When the value in a case statement matches the value of the switch-expression, the statements starting from this case are executed until either a break statement or the end of the switch statement is reached. The default case, which is optional, can be used to perform actions when none of the specified cases matches the switch-expression. The keyword break is optional. The break statement immediately ends the switch statement. Ex: Write a program that reads the month of birth and prints the name of that month. Solution: System.out.print("Enter your birth month, ex 5 : "); int month = input.nextint(); String monthstring; switch (month) { case 1: monthstring = "January"; case 2: monthstring = "February"; case 3: monthstring = "March"; case 4: monthstring = "April"; case 5: monthstring = "May"; case 6: monthstring = "June"; case 7: monthstring = "July"; case 8: monthstring = "August"; case 9: monthstring = "September"; case 10: monthstring = "October"; case 11: monthstring = "November"; case 12: monthstring = "December"; default: monthstring = "Invalid month"; System.out.println(monthString); 8
Conditional Expressions A conditional expression evaluates an expression based on a condition, with no explicit if in the statement. The syntax is boolean-expression? true-expression : false-expression; For example, the two code snippets are equivalent. // with if statement if (x > 0) y = 1; else y = -1; // with conditional expression y = (x > 0)? 1 : -1; Ex: Write a program that reads a number and prints "Even" if the number is even, and "Odd" if the number is odd. Solution: System.out.print("Enter a number: "); int number = input.nextint(); System.out.println((number % 2 == 0)? "Even": "Odd"); Operator Precedence and Associativity Operator precedence and associativity determine the order in which operators are evaluated. Operators are listed in decreasing order of precedence from top to bottom. The logical operators have lower precedence than the relational operators and the relational operators have lower precedence than the arithmetic operators. Operators with the same precedence appear in the same group. 9
All binary operators except assignment operators are left associative. Assignment operators are right associative. Lab Work Ex1: Write a program that prompts the user to enter a decimal number and check if the fractional part is zero or not. 1 st Solution: 10
System.out.print("Enter a number: "); double number = input.nextdouble(); if (number % 1 == 0) System.out.println("fraction is 0"); else System.out.println("fraction isn't 0"); 2 nd Solution: System.out.print("Enter a number: "); double number = input.nextdouble(); System.out.println((number%1 == 0)? "frac. is 0":"frac. not 0"); Ex2: Write a program that reads three edges for a triangle and computes the perimeter if the input is valid. Otherwise, display that the input is invalid. The input is valid if the sum of every pair of two edges is greater than the remaining edge. Solution: System.out.print("Enter edge1: "); double edge1 = input.nextdouble(); System.out.print("Enter edge2: "); double edge2 = input.nextdouble(); System.out.print("Enter edge3: "); double edge3 = input.nextdouble(); if (edge1 + edge2 > edge3 && edge2 + edge3 > edge1 && edge1 + edge3 > edge2) System.out.println("The perimeter is: " + (edge1 + edge2 + edge3)); else System.out.println("Wrong inputs"); Ex3: Write a program that prompts the user to enter a point (x, y) and checks whether the point is within the circle centered at ) 0,0( with radius 10. For example, (4, 5) is inside the circle and (9, 9) is outside the circle. Solution: 11
// Enter a point with two double values System.out.print("Enter a point with two coordinates: "); double x = input.nextdouble(); double y = input.nextdouble(); // Compute the distance double distance = Math.sqrt(x * x + y * y); if (distance <= 10) System.out.println("Point (" + x + ", " + y + ") is in the circle"); else System.out.println("Point (" + x + ", " + y + ") is not in the circle"); Homework 1. (3.8) Write a program that prompts the user to enter three integers and display the integers in increasing order. 2. (3.9) An ISBN-10 (International Standard Book Number) consists of 10 digits: d 1d 2d 3d 4d 5d 6d 7d 8d 9d 10. The last digit, d 10, is a checksum, which is calculated from the other nine digits using the following formula: (d 1 * 1 + d 2 * 2 + d 3 * 3 + d 4 * 4 + d 5 * 5 + d 6 * 6 + d 7 * 7 + d 8 * 8 + d 9 * 9) % 11 If the checksum is 10, the last digit is denoted as X according to the ISBN-10 convention. Write a program that prompts the user to enter the first 9 digits and displays the 10-digit ISBN (including leading zeros). Your program should read the input as an integer. Here are sample runs: Enter the first 9 digits of an ISBN as integer: 013601267 The ISBN-10 number is 0136012671 Enter the first 9 digits of an ISBN as integer: 013031997 The ISBN-10 number is 013031997X Hint: use String.format("%09d", number) to print a number with leading zeros 12
3. (3.26) Write a program that prompts the user to enter an integer and determines whether it is divisible by 5 and 6, whether it is divisible by 5 or 6, and whether it is divisible by 5 or 6, but not both. Here is a sample run: Enter an integer: 10 Is 10 divisible by 5 and 6? false Is 10 divisible by 5 or 6? true Is 10 divisible by 5 or 6, but not both? true 4. (3.33) Suppose you shop for rice in two different packages. You would like to write a program to compare the cost. The program prompts the user to enter the weight and price of each package and displays the one with the better price. Here is a sample run: Enter weight and price for package 1: 50 24.59 Enter weight and price for package 2: 25 11.99 Package 2 has a better price Good Luck 13