Questions for Discussion Week 4 Question 1: Look at the following code segment and predict which if-else statements will run successfully (and print output) and which will give run-time errors. String s1 = null, s2 = "abc"; if (s2.charAt(0) == 'a' || s1.charAt(0) == 'a') // if statement 1 System.out.println("OR 1 True"); else System.out.println("OR 1 False"); if (s2.charAt(0) == 'b' || s1.charAt(0) == 'a') // if statement 2 System.out.println("OR 2 True"); else System.out.println("OR 2 False"); if (s2.charAt(0) == 'b' && s1.charAt(0) == 'b') // if statement 3 System.out.println("AND 1 True"); else System.out.println("AND 1 False"); if (s2.charAt(0) == 'a' && s1.charAt(0) == 'a') // if statement 4 System.out.println("AND 2 True"); else System.out.println("AND 2 False"); 1 Question 2 Predict the output of the following code segment. Can you explain why? double s = 0.0, t; int count = 25; while(count >0) { s += 0.1; // in this loop 0.1 is added to s 25 times. count--; } //What is the value of s at this point of the program? t = 2.5; //Comparison block if (s == t) { System.out.println("s is equal to t"); } else { System.out.println("s is not equal to t"); } Question 3: Which of the following Boolean expressions is equivalent to this Boolean expression? !(x < 0 && y < 0) A. !(x < 0) && !(y < 0) B. !(x >= 0) || !(y >= 0) C. x >= 0 && y >= 0 D. x > 0 && y > 0 E. x >= 0 || y >= 0 2 Question 4: It is a boring Monday again, you are wondering when is Saturday again; hence you decide to write a program to calculate the date of the Saturday. Given a date X1 of a Monday in 2008, calculate what the date X2 of the Saturday in that week is. Input: The date X1 in the form of <day month>. You may assume the date X1 is always a legal date in 2008. Output: The date X2 in the form of <day month>. You may assume the date X2 is in 2008. Sample run #1: Enter date of Monday in <day month>: 25 8 The date of Saturday in that week is 30 8 Sample run #2: Enter date of Monday in <day month>: 29 9 The date of Saturday in that week is 4 10 3 Question 5: Consider the following code fragment that reads a student’s CAP and computes the ranking for his honours degree. public class ProcessCAP { public static void main(String[] args) { double i; Scanner sc = new Scanner(System.in); i = sc.nextDouble(); if (i>=4.5) System.out.println("First class"); if (i>=4.0 && i<=4.5) System.out.println("Second upper"); if (i>=3.5) System.out.println("Second lower"); } } a. b. What is the output of the program if: i = 4.8? i = 4.5? i = 3.0? Any suggestions to make the program more robust? Question 6: Write a program that will take in a string (of length no longer than ten) and determine if the string is palindrome or not. A palindrome is a (see http://www.palindrome.com). We will consider the simplest palindromes where there is no space character in it. Examples of palindrome: “DAD”, “MADAM”, “RACECAR”. 4