int numComparisons, comparisons, a, b, c, scalene, equilateral, isoceles, triangle;
Scanner scan = new Scanner(System.in);
System.out.print("Enter 3 positive integer lengths for the sides of a triangle: ");
a = scan.nextInt();
b = scan.nextInt();
c = scan.nextInt();
System.out.print("The input lengths are: " + a + ", " + b + ", and" + c);
if (a+b>c&&b+c>a&&a+c>b);
System.out.println("The triangle with sides " + a + "," + b + ", and" + c + " is Scalene.");
if (a==b&&b==c)
System.out.println("The triangle with sides " + a + "," + b + ", and" + c + " is Equilateral");
else // (a==b) || (a==c) || (b==c)
System.out.println("The triangle with sides " + a + "," + b + ", and" + c + " is Isoceles");
else
System.out.println("There is no triangle with sides " + a + "," + b + ", and" + c);
回答
看看if (a+b>c&&b+c>a&&a+c>b);
如果一个分号跟在这样的if语句之后,那么如果条件为真(if条件中的任何副作用除外),则不会发生任何反应。
此外,您的缩进不符合您的ifs正在做的事情,您需要大括号以将语句组合在一起。
if (cond) {
statement1;
statement2;
}
没有花括号语句2不是的if语句块,部分:
if (cond)
statement1;
statement2;
然后语句2生效,无论是否COND是真的还是假的。 Java编译器不关心你的缩进。
要回答“我能做什么错”的问题:你在预先编写所有代码,并且只有在全部输入后才能使其工作。一次编写代码并且随时测试。一次编写大量代码只会导致大量的错误需要排序。
因为else
与任何if
都没有关联。
你有一个if
这里,通过本身,它不会做任何事情:。
if (a+b>c&&b+c>a&&a+c>b);
(注意分号这完全终止if
块所以这是名副其实的空if
。块)
如果你想要把这些代码随后的行放到if
块,使用大括号:
if (a+b>c&&b+c>a&&a+c>b) {
System.out.println("The triangle with sides " + a + "," + b + ", and" + c + " is Scalene.");
if (a==b&&b==c)
System.out.println("The triangle with sides " + a + "," + b + ", and" + c + " is Equilateral");
else // (a==b) || (a==c) || (b==c)
System.out.println("The triangle with sides " + a + "," + b + ", and" + c + " is Isoceles");
}
else
System.out.println("There is no triangle with sides " + a + "," + b + ", and" + c);
即使除了分号,只要您有多个语句放入代码块(例如if
块或for
循环)中,您就需要将这些语句与花括号组合在一起。
我会更进一步,并建议使用大括号** ** if **和'else'块。 –
@ Code-Apprentice:这更多的是个人喜好的问题,我不经常分享。该语言允许任何方式。 – David
对于初学者来说,它有助于避免这样的错误。 –
if (a+b>c&&b+c>a&&a+c>b);
这是一个noop。没有花括号的if
只能包含一条指令。这条独特的指令是noop:;
。
使用时如果,而对于等
- 1. jquery if else语句 - 我在做什么错?
- 2. 我得到错误的答案用的if else块
- 3. if else else语法错误C
- 4. Java IF ELSE语法错误
- 5. Java错误'else'没有'if'
- 6. if-else语句错误
- 7. arduino else if语句错误
- 8. Bash if else声明错误
- 9. If-Else Statement C++错误
- 10. javascript if else声明错误
- 11. Python,if-else语句错误
- 12. If-else语句错误'else'without'if'
- 13. PHP的if/else错误
- 14. 错误:else if语句可
- 15. Bash if/else循环错误
- 16. if else语句错误
- 17. JavaScript“if”和“else”错误
- 18. if/elsif/else Ruby错误
- 19. 为什么在输入“else if”时会出现该错误?
- 20. JAVA的if else语句会导致错误在我的代码
- 21. 我遇到了一个我用“else if”语句获得的错误的问题。
- 22. 为什么我得到一个编译错误,说错误:'else'没有以前的'if'?
- 23. if-else vs if-else-if-else
- 24. 为什么我的if else返回false?
- 25. 为什么我会得到“java.lang.IllegalArgumentException”错误?
- 26. 我的'if-else'块在哪里出错?
- 27. 为什么我会得到UncaughtSyntax错误
- 28. 收到没有'if'错误的'else'
- 29. if/if else/else
- 30. 为什么我会得到egg_info错误?
始终使用大括号,您有一个额外的分号,你缺少的括号。 –