简体   繁体   中英

Nested IF statements, trouble completing

The question on my homework is:

Write nested if statements that perform the following test: If amountl is greater than 10 and amount2 is less than 100 , display the greater of the two.

This is what I have so far:

import javax.swing.JOptionPane;

public class nestedif {
    public static void main(String[] args) {
        int amount1, amount2;

        amount1 = JOptionPane.showInputDialog("Enter amount 1: ");
        amount1 = Integer.parseInt(amount1);

        amount2 = JOptionPane.showInputDialog("Enter amount 2: ");
        amount2 = Integer.parseInt(amount2);

        if (amount1>10)

        if (amount2<100)

    }
}

The answers here all work, but everyone seems to have glanced over the instructions. It says write a nested if statement, which is just an if statement inside of another if statement.

You're going to want to do something along the lines of this:

if(amount1 > 10 && amount2 < 100){
    if(amount1 > amount2){
        System.out.println(amount1);
    }
    else{
        System.out.println(amount2);
    }
}

if amountl is greater than 10 and amount 2 is less than 100, display the greater of the two.

You have to 'translate' this statement from plain english to plain Java( or any other programming language )

Translation:

if(amount1 > 10 && amount2 < 100){
    System.out.println(amount1 > amount2 ? amount1 : amount2);
}

or you can use the predefined Java tools which come bundled with the JRE, so you don't have to rewrite the same piece of code over and over again. This version is using the predefined Math.max(int,int)

if(amount1 > 10 && amount2 < 100){
    System.out.println(Math.max(amount1,amount2));
}

Or if you insist, just rewrite the max function by yourself:

public int greaterOfTwo(int first, int second){ // or simply call it max
    return first > second ? first : second;
}

if(amount1 > 10 && amount2 < 100){
    System.out.println(greaterOfTwo(amoun1,amount2));
}

int amount1, amount2; String input1, input2;

input1 = JOptionPane.showInputDialog("Enter the amount:");
amount1 = Integer.parseInt(input1);

input2 = JOptionPane.showInputDialog("Enter the second amount:");
amount2 = Integer.parseInt(input2);

if(amount1 > 10 && amount2 < 100)
{
if(amount1 > amount2)
{
    JOptionPane.showMessageDialog(null, "Amount 1 is the greater amount of " + amount1);
}
else
{
    JOptionPane.showMessageDialog(null,"Amount 2 is the greater amount of " + amount2);
}
}
else
{
JOptionPane.showMessageDialog(null, "Type the number greater than 10 or less than 100.");
}

System.exit(0);

}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM