英文:
Why won't this code segment produce a result?
问题
我需要在 Java 中修复这段代码,我正在使用 Eclipse
(total == MAX)
if (total < sum)
System.out.println("total == MAX and < sum.");
else
System.out.println("total is not equal to MAX");
package lecture1_1;
public class Total {
public static void main(String[] args) {
int MAX = 100;
int total = 50;
int sum = 150;
if (total == MAX)
if (total < sum)
System.out.println("total is equal to MAX and less than sum.");
else
System.out.println("total is not equal to MAX");
}
}
但它没有输出结果。我漏掉了什么吗?
英文:
I need to fix this block of code in java, I am using eclipse
(total == MAX)
if (total < sum)
System.out.println("total == MAX and < sum.");
else
System.out.println("total is not equal to MAX");
so i made my adjustments and got this
package lecture1_1;
public class Total {
public static void main(String[] args) {
int MAX = 100;
int total = 50;
int sum = 150;
if (total == MAX)
if (total < sum)
System.out.println("total is equal to MAX and less than sum.");
else
System.out.println("total is not equal to MAX");
}
}
but it prints no result. what am i missing?
答案1
得分: 2
TL;DR 使用大括号来确定代码块的边界 - 这将使代码更易读。
你期望的是这样的:
public static void main(String[] args) {
int MAX = 100;
int total = 50;
int sum = 150;
if (total == MAX) {
if (total < sum) {
System.out.println("total is equal to MAX and less than sum.");
}
}
else {
System.out.println("total is not equal to MAX");
}
}
但你现在的代码是这样的:
public static void main(String[] args) {
int MAX = 100;
int total = 50;
int sum = 150;
if (total == MAX) {
if (total < sum) {
System.out.println("total is equal to MAX and less than sum.");
}
else {
System.out.println("total is not equal to MAX");
}
}
}
英文:
TL;DR use brackets to establish code block boundaries - it will make code more readable.
What you're expecting is this:
public static void main(String[] args) {
int MAX = 100;
int total = 50;
int sum = 150;
if (total == MAX) {
if (total < sum) {
System.out.println("total is equal to MAX and less than sum.");
}
}
else {
System.out.println("total is not equal to MAX");
}
}
But what you have is this:
public static void main(String[] args) {
int MAX = 100;
int total = 50;
int sum = 150;
if (total == MAX) {
if (total < sum) {
System.out.println("total is equal to MAX and less than sum.");
}
else {
System.out.println("total is not equal to MAX");
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论