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!");
}
}
}
谁能解释一下为什么这个程序会返回有足够的零食给所有的仓鼠!"不管是否neededTreats">treatsPerHamster"?
Can someone explain to me why this program returns "There are enough treats for all the hamsters!" regardless of whether "neededTreats" > "treatsPerHamster"?
谢谢.
推荐答案
您正在将值 true 分配给 enoughtreats.
You are assigning the value true to enoughtreats.
尝试使用相等运算符而不是赋值:
Try using the equality operator rather than assignment:
if (enoughtreats == true) {
...
}
或者简单地说:
if(enoughtreats) {
...
}
这篇关于如果语句总是给出相同的答案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如果语句总是给出相同的答案
基础教程推荐
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 降序排序:Java Map 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01