19.09.2015 Views

Prentice.Hall.Introduction.to.Java.Programming,.Brief.Version.9th.(2014).[sharethefiles.com]

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

112 Chapter 3 Selections<br />

The result of this conditional expression is expression1 if boolean-expression is true;<br />

otherwise the result is expression2.<br />

Suppose you want <strong>to</strong> assign the larger number of variable num1 and num2 <strong>to</strong> max. You can<br />

simply write a statement using the conditional expression:<br />

max = (num1 > num2) ? num1 : num2;<br />

For another example, the following statement displays the message “num is even” if num is<br />

even, and otherwise displays “num is odd.”<br />

System.out.println((num % 2 == 0) ? "num is even" : "num is odd");<br />

As you can see from these examples, conditional expressions enable you <strong>to</strong> write short and<br />

concise code.<br />

Note<br />

The symbols ? and : appear <strong>to</strong>gether in a conditional expression. They form a conditional<br />

opera<strong>to</strong>r called a ternary opera<strong>to</strong>r because it uses three operands. It is the only<br />

ternary opera<strong>to</strong>r in <strong>Java</strong>.<br />

✓Point✓ Check<br />

3.33 Suppose that, when you run the following program, you enter input 2 3 6 from the<br />

console. What is the output?<br />

public class Test {<br />

public static void main(String[] args) {<br />

java.util.Scanner input = new java.util.Scanner(System.in);<br />

double x = input.nextDouble();<br />

double y = input.nextDouble();<br />

double z = input.nextDouble();<br />

}<br />

}<br />

System.out.println((x < y && y < z) ? "sorted" : "not sorted");<br />

3.34 Rewrite the following if statements using the conditional opera<strong>to</strong>r.<br />

if (ages >= 16)<br />

ticketPrice = 20;<br />

else<br />

ticketPrice = 10;<br />

if (count % 10 == 0)<br />

System.out.print(count + "\n");<br />

else<br />

System.out.print(count);<br />

3.35 Rewrite the following conditional expressions using if-else statements.<br />

a. score = (x > 10) ? 3 * scale : 4 * scale;<br />

b. tax = (in<strong>com</strong>e > 10000) ? in<strong>com</strong>e * 0.2 : in<strong>com</strong>e * 0.17 + 1000;<br />

c. System.out.println((number % 3 == 0) ? i : j);<br />

Key<br />

Point<br />

3.16 Formatting Console Output<br />

You can use the System.out.printf method <strong>to</strong> display formatted output on the console.<br />

Often it is desirable <strong>to</strong> display numbers in a certain format. For example, the following code<br />

<strong>com</strong>putes interest, given the amount and the annual interest rate.<br />

double amount = 12618.98;<br />

double interestRate = 0.0013;

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!