1. Suppose x = 3 and y = 2; show the output, if any, of the following code. What is the output if x = 3 and y = 4? What is the output of x = 2 and y = 2?
if (x > 2)
{
if (y > 2)
{
z = x + y;
System.out.println (“z is ” +z);
}
}
else
{
System.out.println (“x is ” +x);
Jawaban :
Jika dimisalkan x = 3 dan y = 2, tidak ada keluar hasil output dari coding yang telah kita buat.
Jika dimisalkan x = 3 dan y = 4, maka hasil output dari coding yang kita lakukan adalah z is 7
Jika dimisalkan x = 2 dan y = 2, maka hasil output dari coding yang kita lakukan adalah x is 2
2. What is y after the following switch statement is executed?
x = 3; y = 3
switch (x = 3)
{
case 6: y = 1;
default: y += 1;
}
Jawaban :
x |
3 |
y |
3 |
x |
3 |
y |
1 |
x |
3 |
y |
2 |
Maka, hasil y adalah 2
3. Use a switch statement to rewrite the following if statement
if (a == 1)
x += 5;
else if (a == 2)
x += 10;
else if (a == 3)
x += 16;
else if (a == 4)
x += 34;
Jawaban :
import java.util.Scanner;
public class Soal4Cnomor3
{
public static void main (String[]args)
{
int a;
int x;
Scanner input = new Scanner (System.in);
System.out.print (“Input a [1 – 4] : “);
x = input.nextInt();
switch (x)
{
case 1:
System.out.print (“x = “);
System.out.println(x+=5);
break;
case 2:
System.out.print (“x = “);
System.out.println (x+= 10);
break;
case 3:
System.out.print (“x = “);
System.out.println (x+=16);
break;
case 4:
System.out.print (“x = “);
System.out.println (x+=34);
break;
default:
System.out.println (“Silahkan memilih angka 1, 2, 3, dan 4”);
}
}
}
4. Use a ternary operator to rewrite the following if statement
if (x >65)
System.out.println (“Passed”);
else
System.out.println (“Failed”);
Jawaban :
import java.util.Scanner;
public class Soal4Cnomor4
{
public static void main (String[]args)
{
int x;
Scanner input = new Scanner (System.in);
System.out.print (“Input a value [0 – 100] : “);
try
{
x = input.nextInt();
if (x >65)
System.out.println (“Passed”);
else
System.out.println (“Failed”);
}
catch (Exception e)
{
System.out.println (“Input must be number”);
}
}
}
( Novianti – 1701298144 )
http://www.binus.ac.id
Leave a Reply