Java Reference
In-Depth Information
with a one-liner. We can do that when we assign different values to the same variable based
on the validity of a condition. Recall our arithmetic game example.
1 import java . util . ;
2 public class Arithmetic
{
3
public static void main(String [] args)
{
4
int x=( int )
(Math . random ( )
10) ;
5
int y=( int )
(Math . random ( )
10) ;
6
Scanner keyboard = new Scanner(System. in) ;
7
System . out . p r i n t ( x + "*" +y+ "=" );
8
int z = keyboard . nextInt () ;
9
if (z == x
y)
{
10
System . out . p r i n t l n ( "Congratulations!" );
11
}
else
{
12
System . out . p r i n t l n ( "You need more practice" );
13
}
14
}
15 }
We will rewrite the code to use the new construct. We will create a variable output of
type String . The value of the output will depend on whether the user guessed the correct
result. Now Lines 9-13 can be rewritten as follows.
String output;
if (z == x y) {
output = "Congratulations!" ;
} else {
output = "You need more practice" ;
System. out . println (output) ;
Now, we can use the “?:” constructor to rewrite the code as follows.
String output;
output = (z == x y) ? "Congratulations!" : "You need more practice" ;
System. out . println (output) ;
The general syntax of the conditional operator is x = (condition)? value1 :
value2 .Ifthe condition is true, then x becomes equal to value1 . Otherwise, x is
assigned the value of value2 .
The rewritten game follows.
import java . util . ;
public class Arithmetic {
public static void main(String [] args)
{
int x=( int ) (Math . random ( ) 10) ;
int y=( int ) (Math . random ( ) 10) ;
Scanner keyboard = new Scanner(System. in) ;
System. out . print (x + "*" +y+ "=" );
int z = keyboard . nextInt () ;
String output;
output = (z == x
y) ? "Congratulations!" : "You need more
practice" ;
System. out . println (output) ;
}
 
Search WWH ::




Custom Search