I am trying to make a method that tests to see if 3 lengths can make a triangle. 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)
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
. Try using 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 .
Personally, I don't like if/else
very much.
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.
You can't have two else
s for the same if. Change your nesting so that you use else if
rather than
else
{
if
看起来问题是你有多个else块,一个if语句只能有一个else块。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.