[英]What's wrong with this conditional?
I am trying to make a method that tests to see if 3 lengths can make a triangle. 我正在尝试制作一个方法,测试3个长度是否可以形成三角形。 I think i'm making some kind of syntax error but i can't figure out what it is.
我想我正在制作某种语法错误,但我无法弄清楚它是什么。
Here is the relevant bit of code: (its in java) 这是相关的代码:(在java中)
public static void trya (int a, int b, int c)
{
if (c>(a+b))
{
System.out.println ("yes") ;
}
else
{
if (b>(a+c))
{
System.out.println ("yes") ;
}
}
else
{
if (a>(b+c))
{
System.out.println ("yes") ;
}
}
else
{
System.out.println ("no") ;
}
}
this is the error message i get: 这是我得到的错误消息:
tryangle.java:17: 'else' without 'if'
else
^
You have two else
blocks for the first if
. 第一个
if
有两个else
块。 Try using else if
: 尝试使用
else if
:
public static void trya (int a, int b, int c)
{
if (c>(a+b))
{
System.out.println ("yes") ;
}
else if (b>(a+c))
{
System.out.println ("yes") ;
}
else if (a>(b+c))
{
System.out.println ("yes") ;
}
else
{
System.out.println ("no") ;
}
}
当你还是学生时,我认为我可能会指出Java在线文档的控制流语句部分。
This is invalid: 这是无效的:
if (cond A) {
// ...
} else {
if (cond B) {
// ...
}
} else {
if (cond C) {
// ...
}
}
It should rather be: 它应该是:
if (cond A) {
// ...
} else if (cond B) {
// ...
} else if (cond C) {
// ...
}
Learn more at this Sun tutorial . 在本Sun教程中了解更多信息。
Personally, I don't like if/else
very much. 就个人而言,我不喜欢
if/else
。
public static boolean isValidTriangle(int a, int b, int c)
{
return (c > a + b) || (b > a + c) || (a > b + c);
}
public static void trya(int a, int b, int c)
{
System.out.println(isValidTriangle(a, b, c) ? "yes" : "no");
}
It should be: 它应该是:
public static void trya (int a, int b, int c)
{
if (c>(a+b))
{
System.out.println ("yes") ;
}
else if (b>(a+c))
{
System.out.println ("yes") ;
}
else if (a>(b+c))
{
System.out.println ("yes") ;
}
else
{
System.out.println ("no") ;
}
}
This is how your code is formatted: 这是您的代码格式化的方式:
if (...) {...}
else {...}
else {...} //else than what?
It may also be worth pointing out that your method doesn't actually test to see if three lengths can make a triangle. 值得指出的是,您的方法实际上并未测试三个长度是否可以形成三角形。 For example,
trya(1, 1, 4)
will result in printing yes
even though the side lengths 1, 1, 4 do not form a triangle. 例如,即使边长
trya(1, 1, 4)
不形成三角形, trya(1, 1, 4)
也会导致打印为yes
。
You can't have two else
s for the same if. 你不能有两个
else
S为相同的,如果。 Change your nesting so that you use else if
rather than 更改您的嵌套,以便您使用
else if
而不是
else
{
if
看起来问题是你有多个else块,一个if语句只能有一个else块。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.