Exercise
Conditional operator, positive & smaller
Objetive
Write a java program that asks the user for two numbers and answers, using the conditional operator (?), for the following:
If the first number is positive
If the second number is positive
If both are positive
Which one is smaller
Example Code
import java.util.*;
public class Main
{
public static void main(String[] args)
{
int a, b;
String answer;
System.out.print("Enter the first number: ");
a = Integer.parseInt(new Scanner(System.in).nextLine());
System.out.print("Enter the second number: ");
b = Integer.parseInt(new Scanner(System.in).nextLine());
if (a > 0)
{
System.out.println("a is positive");
}
else
{
System.out.println("a is not positive");
}
if (a > 0)
{
answer = "a is positive";
}
else
{
answer = "a is not positive";
}
System.out.println(answer);
answer = a > 0 ? "a is positive" : "a is not positive";
System.out.println(answer);
System.out.println(b > 0 ? "b is positive" : "b is not positive");
answer = (a > 0) && (b > 0) ? "both are positive" : "not both are positive";
System.out.println(answer);
int smallest = a < b ? a : b;
System.out.printf("Smallest: %1$s" + "\r\n", smallest);
}
}