The if statement is used to implement a decision. The simplest form of an if sta
ID: 3812852 • Letter: T
Question
The if statement is used to implement a decision. The simplest form of an if statement has two parts: a condition and a body. If the condition is true, the body of the statement is executed. The body of the if statement consists of a statement block.
Consider the following program, which uses an if statement to output the smaller (minimum) of two numbers:
import java.io.*;
import java.util.*;
public class CPS150_Lab12
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
PrintStream disp = System.out;
// input variables
int x;
int y;
// output variable
int min;
disp.println("Enter a value for x:");
x = scan.nextInt();
disp.println("Enter a value for y:");
y = scan.nextInt();
min = x; // assume x is smaller
if (y < min)
{
min = y;
}
disp.println("The smallest value is " + min);
} // end main method
} // end class SmallestInt
Lab 12.1
First, copy-and-paste the highlighted code above to the main method of your NetBeans project. Then, modify the code so that it prompts the user to enter a third value for a variable z. Rewrite the logic so that the program prints out the smallest value contained in x, y, and z.
Lab 12.2
Modify the code from Lab 8.1 so that it prompts the user for four integers (w, x, y, and z) and prints the smallest value contained in those variables.
this is the code for lab 8.1
Explanation / Answer
For Lab 12.1, below is the code. Here we take one more variable z and ask the user to enter the alue for it. The minimum value comparision logic is then extended to the third variable. In a similar fashion, we can have 4 variables if required and exend the check for minimum value to fourth variable.
package chegg;
import java.io.*;
import java.util.*;
public class CPS150_Lab12
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
PrintStream disp = System.out;
// input variables
int x;
int y;
int z;
// output variable
int min;
disp.println("Enter a value for x:");
x = scan.nextInt();
disp.println("Enter a value for y:");
y = scan.nextInt();
disp.println("Enter a value for z:");
z = scan.nextInt();
min = x; // assume x is smaller
if (y < min)
{
min = y;
}
if (z < min)
{
min = z;
}
disp.println("The smallest value is " + min);
} // end main method
} // end class SmallestInt
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.