Skip to content

Instantly share code, notes, and snippets.

@dhust
Last active May 23, 2017 00:08
Show Gist options
  • Save dhust/6134821 to your computer and use it in GitHub Desktop.
Save dhust/6134821 to your computer and use it in GitHub Desktop.
If statement comparing numbers
public static void main(String[] args) {
// Variables
Scanner input = new Scanner(System.in);
int age;
// Ask a question and save their answer
System.out.print("Enter your age: ");
age = input.nextInt();
// Output text based on their answer
if (age >= 18) {
System.out.println("You can vote.");
}
else {
// If the if statement above doesn't run, then this code will run
System.out.println("You aren't old enough to vote.");
}
}
@dhust
Copy link
Author

dhust commented Aug 1, 2013

The most common mistake using if statements and comparing numbers is knowing when to use = and when to use ==.
Use = when you want to set a variable to a number, like "int num = 5;"
Use == when you are comparing two numbers, like "num == 7;" This would return True if num = 7, but it would return False if num = 8 (or any other number but 7).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment