Reputation: 5
import java.util.Scanner;
public class FantahunKeburAlmostIsoscelesRightTriangle{
public static void main (String []args){
Scanner s = new Scanner(System.in);
System.out.println("Enter the longest side: ");
double longest = s.nextDouble();
System.out.println("Enter 2nd side: ");
double second = s.nextDouble();
System.out.println("Enter 3rd side: ");
double third = s.nextDouble();
double longsq = longest*longest;
double secondsq = second*second;
double thirdsq = third*third;
double secthirdsq = secondsq*thirdsq;
if (secthirdsq==longsq)
{
System.out.println("This triangle is an almost-Isosceles right triangle. ");
}
else if (secthirdsq!=longsq)
{
System.out.println("This triangle is not a right triangle. ");
}}
Here is the error I'm getting this>> .java:31: error: 'else' without 'if' else if (secthirdsq!=longsq); ^ 1 error
I need it to print the first statement after the if not the one after else if
Edit: I changed it and now I am not able to get the first print line to print even when the first if-statement is true
Upvotes: 1
Views: 120
Reputation: 5496
You have a semi colon at the end of your if statement. That semi colon ends the if statement, and the next block of code is seen as just a block and is executed no matter what.
You need to remove all your semi colons at the end of your if statements:
if (secthirdsq==longsq)
{
...
}
else if (secthirdsq!=longsq)
{
...
Also your code looks to suffer from the inaccuracy of floating point calculations, try to compare like:
if (Math.abs(secthirdsq-longsq) < 0.001))
or just use whole numbers (like int). In addition, you probably just want an else instead of that else if, as you are comparing the opposite of what the preceding if is comparing.
Upvotes: 2
Reputation: 5056
There are semicolons (;
) after your if statements. This doesn't work.
It's basically saying if condition is true, do nothing. And then it executes the code in the {}
s. (Java allows for random {}
s like this).
To correct your code:
import java.util.Scanner;
public class FantahunKeburAlmostIsoscelesRightTriangle{
public static void main (String []args){
Scanner s = new Scanner(System.in);
System.out.println("Enter the longest side: ");
double longest = s.nextDouble();
System.out.println("Enter 2nd side: ");
double second = s.nextDouble();
System.out.println("Enter 3rd side: ");
double third = s.nextDouble();
double longsq = longest*longest;
double secondsq = second*second;
double thirdsq = third*third;
double secthirdsq = secondsq*thirdsq;
if (secthirdsq==longsq) {
System.out.println("This triangle is an almost-Isosceles right triangle. ");
}
else if (secthirdsq!=longsq) {
System.out.println("This triangle is not a right triangle. ");
}
}
}
As a side note, I recommend (though this is a personal preference) that you put the {
s for if statements on the same line. It will make errors like this more obvious - if (condition); {
looks wrong at first glance.
Upvotes: 1