What's wrong with this conditional?
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 e开发者_JAVA百科rror 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") ;
}
}
As you're a student, I think it's probably appropriate that I point you to the Control Flow Statements part of the Java online documentation.
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
It looks like the problem is you have multiple else blocks, one if statement can have only one else block.
精彩评论