Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
198 views
in Technique[技术] by (71.8m points)

java - If statement always giving the same answer

import java.util.Scanner;

class Practice {

public static void main(String args[]) {

    System.out.println("Enter the number of treats you have:");
    Scanner treatsScanner = new Scanner(System.in);
    int treats = (treatsScanner.nextInt());

    System.out.println("Enter the number of hamsters you have:");
    Scanner hamstersScanner = new Scanner(System.in);
    int hamsters = (hamstersScanner.nextInt());

    System.out.println("How many treats does each hamster need?");
    Scanner neededTreatsScanner = new Scanner(System.in);
    int neededTreats = (neededTreatsScanner.nextInt());     

    int treatsPerHamster = treats / hamsters;
    boolean enoughTreats = treatsPerHamster >= neededTreats;        

    if (enoughTreats = true) {
        System.out.println("There are enough treats for all the hamsters!");
    }
    else if (enoughTreats = false) {
        System.out.println("Oh no! There aren't enough treats!");        
    }

}
}

Can someone explain to me why this program returns "There are enough treats for all the hamsters!" regardless of whether "neededTreats" > "treatsPerHamster"?

Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...