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. ");
}}
以下是错误我得到的>> .java:31:错误:'否则'没有'如果' 否则if(secthirdsq!= longsq); ^ 1错误
我需要它来打印if之后的第一个语句,如果
编辑:我更改了它,现在即使第一个if语句为真,我也无法打印第一个打印行
答案 0 :(得分:2)
if语句的末尾有一个半冒号。该半冒号结束if语句,下一个代码块被视为一个块,无论如何都会被执行。
您需要在if语句末尾删除所有半冒号:
if (secthirdsq==longsq)
{
...
}
else if (secthirdsq!=longsq)
{
...
此外,您的代码看起来会受到浮点计算不准确的影响,请尝试比较:
if (Math.abs(secthirdsq-longsq) < 0.001))
或只使用整数(如int)。另外,你可能只想要一个else而不是那个,如果你正在比较前面的if比较的那个。
答案 1 :(得分:1)
在if语句后面有分号(;
)。这不起作用。
基本上说如果情况属实,什么都不做。然后它执行{}
中的代码。 (Java允许这样的随机{}
)。
更正您的代码:
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. ");
}
}
}
作为旁注,我建议(尽管这是个人偏好),您将if语句的{
放在同一行。它会使这样的错误更明显 - if (condition); {
乍一看看起来不对劲。