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!");
}
}
}
有人可以向我解释为什么这个程序返回“所有的仓鼠都有足够的零食!”不管是否“neededTreats”>“treatsPerHamster”?
谢谢。
最佳答案
你应该使用 ==
而不是 =
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!");
}
请记住,==
是比较运算符,=
是赋值运算符。
正如 Mike 所提到的,只需使用 if(enoughTreats)
就可以解决问题。无需使用 ==
运算符!
事实上,您根本不需要 boolean 变量 enoughTreats
。你可以这样写你的条件:
if (treatsPerHamster >= neededTreats) {
// do one thing
}
else {
// do other
}
关于java - If 语句总是给出相同的答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6350680/