import java.lang.Character; import javax.swing.JOptionPane; public class If { // use if - else if - else to handle multiple alternatives public void ifExample() {String ageStr = JOptionPane.showInputDialog("How old are you?"); int age = Integer.parseInt(ageStr); String msg; if (age >= 18) { msg = "You can get a full driver's license"; } else if (age == 17) msg = "You can get a provisional license"; else if (age == 16) msg = "You can get a learner's permit"; else msg = "You can get a learner's permit when you're 16"; JOptionPane.showMessageDialog(null, msg); } public void compareNumbers() { double r = Math.sqrt(2); double d = r * r - 2; // to compare 2 floating-point numbers, see if // their difference is less than some tolerance, // here, 1e-15. if (d < 1e-15) System.out.println("sqrt(2) squared minus 2 is 0"); else System.out.println("sqrt(2) squared minus 2 is " + d); } // use .equals() to compare Strings and any objects // using compareTo() is also an option public void compareStrings() { String n1 = "Irene"; String n2 = "Lingnan"; String msg = ""; if (n1.equals(n2)) msg = "They match"; else msg = "They DON'T match"; //JOptionPane.showMessageDialog(null, msg); String n3 = "Josh", n4 = "josh"; if (n3.equalsIgnoreCase(n4)) msg = "They match"; else msg = "They DON'T match"; //JOptionPane.showMessageDialog(null, msg); int result = n3.compareTo(n4); JOptionPane.showMessageDialog(null, result); } public double taxReturn() { final int SINGLE = 1; final int MARRIED = 2; final double RATE1 = 0.10; final double RATE2 = 0.25; final double RATE1_SINGLE_LIMIT = 32000; final double RATE1_MARRIED_LIMIT = 64000; double income; int status; String incomeStr, statusStr; incomeStr = JOptionPane.showInputDialog("Income? "); statusStr = JOptionPane.showInputDialog("Marital status?"); income = Double.parseDouble(incomeStr); status = Integer.parseInt(statusStr); double tax1 = 0, tax2 = 0; // you can "nest" IF statements if (status == SINGLE) { if (income <= RATE1_SINGLE_LIMIT) tax1 = RATE1 * income; else { tax1 = RATE1 * RATE1_SINGLE_LIMIT; tax2 = RATE2 * (income - RATE1_SINGLE_LIMIT); } } else if (status == MARRIED) { if (income <= RATE1_MARRIED_LIMIT) tax1 = RATE1 * income; else { tax1 = RATE1 * RATE1_MARRIED_LIMIT; tax2 = RATE2 * (income - RATE1_MARRIED_LIMIT); } } return tax1 + tax2; } public void trueOrFalse() { double amount = 0; System.out.println(amount < 1000); // return amount < 1000; // Some methods, like isDigit(), return a boolean: System.out.println(Character.isDigit('$')); System.out.println(Character.isDigit('3')); // Some expressions evaluate to a boolean: System.out.println(amount > -1000 && amount < 1000); System.out.println(amount < -100 || amount < 100); } public static void main(String[] args) { If i = new If(); // i.ifExample(); //i.compareNumbers(); //i.compareStrings(); //double tax = i.taxReturn(); //String msg = "The tax is " + tax; //JOptionPane.showMessageDialog(null, msg); i.trueOrFalse(); } }