package ch5a; import javax.swing.JOptionPane; public class Ch5a { private double balance = 1000; // example of an if statement with 2 branches public void withdraw(double amount) { if (balance >= amount) { balance = balance - amount; // shorthand: balance -= amount; String msg = "Amount withdrawn: $" + amount; msg += " Current balance: $" + balance; JOptionPane.showMessageDialog(null,msg); } else { String msg2 = "Insufficient funds"; JOptionPane.showMessageDialog(null,msg2); } // comparing doubles double r = Math.sqrt(2); double d = r * r - 2; if (d == 0) JOptionPane.showMessageDialog(null,"they're the same") ; else JOptionPane.showMessageDialog(null,"d = " + d); // this doesn't work due to roundoff error //compare doubles by seeing if they are "close enough" if (d < 1e-15) JOptionPane.showMessageDialog(null,"they're the same") ; else JOptionPane.showMessageDialog(null,"d = " + d); } // example of if statement with multiple branches public void richter(double r) { String m; if (r >= 8.0) m = "Most structures fall"; else if (r >= 7.0) m = "Many buildings destroyed"; else if (r >= 6.0) m = "Many buildings considerably damaged"; else if (r >= 4.5) m = "Damage to poorly constructed buildings"; else if (r >= 3.5) m = "Felt by many people, no destruction"; else if (r >= 0) m = "Generally not felt by people"; else m = "Negative numbers are not valid"; JOptionPane.showMessageDialog(null, m); } // example of nested if statements public void taxes(double income, String status) { double tax; if (status.equals("single")) { if (income <= 32000) { tax = income * 0.1; } else { tax = 3200 + (income-32000) * 0.25; } } else { if (income <= 64000) { tax = income * 0.1; } else { tax = 6400 + (income-64000) * 0.25; } } String msg = "Your tax owed is $" + tax; JOptionPane.showMessageDialog(null, msg); } public static void main(String[] args) { Ch5a c = new Ch5a(); c.withdraw(100); c.richter(7.1); c.taxes(100000, "married"); } }