import java.util.Scanner;
class Practice {
public static void main(String args[]) {
System.out.println(\"Enter the number of treats you have:\");
Scanner
Few things to note and to add to the listed answers
Scanner inputScanner = new Scanner(System.in);
(...Scanner.nextInt());
is not really necessary hamsters
!else if(){}
is not required when if(){}
has only single boolean check , just an else{
is sufficient You are assigning the value true to enoughtreats.
Try using the equality operator rather than assignment:
if (enoughtreats == true) {
...
}
or simply:
if(enoughtreats) {
...
}
Use ==
for equality, not =
.
In java, the '=' operator assigns a value to a variable. In this case,
if (enoughTreats = true)
assigns the value 'true' to 'enoughTreats' and then checks if 'enoughTreats' is true (which it always will be).
Instead, you want to put
if (enoughTreats == true)
so that it will check if enoughTreats is true or false.
You need to change these two statements
if (enoughTreats = true)
else if (enoughTreats = false)
into
if (enoughTreats == true)
else if (enoughTreats == false)
You could also shorten the code and get the exact same effect by simply typing this below:
if (enoughTreats)
else
If you put a boolean variable inside of the parenthesis of an if statement by itself, the if statement will check to see if it's true, thus you wouldn't need to type '== true.' You could also replace the else if statement in your code with a simple 'else' because if the enoughTreats variable is not equal to true, the else code will automatically execute without you having to specifically state a condition.
You should use ==
instead of =
if (enoughTreats == true) {
System.out.println("There are enough treats for all the hamsters!");
}
else {
System.out.println("Oh no! There aren't enough treats!");
}
Remember that ==
is the comparison operator and =
is the assignment operator.
And as Mike mentioned, just having if(enoughTreats)
will do the trick for you. No need to use ==
operator!
As a matter of fact, you don't need the boolean variable enoughTreats
at all. You could just write your condition like so:
if (treatsPerHamster >= neededTreats) {
// do one thing
}
else {
// do other
}