public class ElevatorFitter2 {
public static void main(String[] args) {
int weightOfAPerson = 150;
int elevatorWeightLimit = 1400;
int numberOfPeople = elevatorWeightLimit / weightOfAPerson;
if (numberOfPeople >= 10) {
System.out.println("You can fit all ten of the");
} else {
System.out.println("You can't fit all ten of the");
}
System.out.println("Brickenchicker dectuplets");
System.out.println("on the elevator.");
}
}
The program still works because username != null &&
password != null is logically equivalent to !(username
== null || password == null). This is so because of
DeMorgan's Law of logic. It's a kind of distributive law for the !,
&&, and || operators.
The program crashes if the user clicks the Cancel button in one of
the JOptionPane.showInputDialog calls. This happens
because the condition !(username == null && password
== null) isn't logically equivalent to the condition in the
original program. Assume, for example, that the user types bburd
in the Username: dialog box but clicks the Cancel
button in the Password: dialog box. Then the value of
username is bburd but the value of password
is null (meaning that password doesn't
have a valid String value). Then the condition !(username
== null && password == null) is true
because it's not the case that both username and password
are null. So Java goes on to check if username.equals("bburd"),
which it does. So then Java goes on to check if password.equals("swordfish").
But trying to call the equals method on the password
variable causes the program to crash, because password
isn't a valid String value. Instead, password
is null.
public static void main(String[] args) { var keyboard = new Scanner(System.in);
System.out.print("Enter the name of a month: "); String month = keyboard.next();
int numDays = switch (month) { case "January", "March", "May", "July", "August", "October", "December" -> 31; case "February" -> 28; case "April", "June", "September", "November" -> 30; default -> 0; };
System.out.print("Is it a leap year (yes/no)? "); String isLeapYear = keyboard.next();
if (month.equals("February") && isLeapYear.equals("yes")) { numDays = 29; }
System.out.print(month + " has "); System.out.print(numDays); System.out.println(" days."); } }
import java.util.Scanner;
public class Main {
public static void main(String[] args) { var keyboard = new Scanner(System.in);
System.out.print("Enter the name of a month: "); String month = keyboard.next();
int numDays = 0;
switch (month) { case "January": case "March": case "May": case "July": case "August": case "October": case "December": numDays = 31; break; case "February": numDays = 28; break; case "April": case "June": case "September": case "November": numDays = 30; break; }
System.out.print("Is it a leap year (yes/no)? "); String isLeapYear = keyboard.next();
if (month.equals("February") && isLeapYear.equals("yes")) { numDays = 29; }
System.out.print(month + " has "); System.out.print(numDays); System.out.println(" days."); } }