2.2 Construct a logical expression to represent each of the following conditions
ID: 642578 • Letter: 2
Question
2.2 Construct a logical expression to represent each of the following conditions:
a. x is between 3 and 15 but not equal to 10. b. x is between 10 and 20 but not odd.
c. y is divisible by 5 but not by 40.
d. str is a lowercase or uppercase letter.
2.3 What is the difference between the following two statements?
if (n > 2) { if (n < 6) System.out.println("Done!"); } else System.out.println("Error");
if (n > 2) { if (n < 6) System.out.println("Done!"); else System.out.println("Error"); }
2.4 What is the difference between the result of the following two statements?
int cents = (int)(100 * price + 0.5);
int cents = (100 * price + 0.5);
Explanation / Answer
2.2 Construct a logical expression to represent each of the following conditions:
a. x is between 3 and 15 but not equal to 10.
if ((x > 2) && (x < 16) && (x != 10))
b. x is between 10 and 20 but not odd.
if ((x > 9) && (x < 21) && (x % 2 == 0))
c. y is divisible by 5 but not by 40.
if ((y % 5 == 0) && (y % 40 != 0))
d. str is a lowercase or uppercase letter.
if (Character.isUpperCase(str.charAt(0))) // str is uppercase letter
else // str is lowercase letter
2.3 What is the difference between the following two statements?
if (n > 2)
{
if (n < 6)
System.out.println("Done!");
}
else
System.out.println("Error");
if (n > 2)
{
if (n < 6)
System.out.println("Done!");
else
System.out.println("Error");
}
First statement: print "Error" when n <= 2, print "Done" when n > 2 and n < 6
Second statement: print "Error" when n > 2 and n >= 6, print "Done" when n < 6
2.4 What is the difference between the result of the following two statements?
int cents = (int)(100 * price + 0.5);
int cents = (100 * price + 0.5);
First statement: explicit cast the result (100 * price + 0.5) to int before assign the value to cents
Seond statement: compilation error int java because (100 * price + 0.5) is not a int, but a float or double. Java will not do implicit conversion
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.