2016-02-19 35 views
0
int numComparisons, comparisons, a, b, c, scalene, equilateral, isoceles, triangle; 
Scanner scan = new Scanner(System.in); 
System.out.print("Enter 3 positive integer lengths for the sides of a triangle: "); 
a = scan.nextInt(); 
b = scan.nextInt(); 
c = scan.nextInt(); 
System.out.print("The input lengths are: " + a + ", " + b + ", and" + c); 
if (a+b>c&&b+c>a&&a+c>b); 
System.out.println("The triangle with sides " + a + "," + b + ", and" + c + " is Scalene."); 
if (a==b&&b==c) 
    System.out.println("The triangle with sides " + a + "," + b + ", and" + c + " is Equilateral"); 
else // (a==b) || (a==c) || (b==c) 
    System.out.println("The triangle with sides " + a + "," + b + ", and" + c + " is Isoceles"); 
else 
    System.out.println("There is no triangle with sides " + a + "," + b + ", and" + c); 
+1

始终使用大括号,您有一个额外的分号,你缺少的括号。 –

回答

1

看看if (a+b>c&&b+c>a&&a+c>b);如果一个分号跟在这样的if语句之后,那么如果条件为真(if条件中的任何副作用除外),则不会发生任何反应。

此外,您的缩进不符合您的ifs正在做的事情,您需要大括号以将语句组合在一起。

if (cond) { 
    statement1; 
    statement2; 
} 

没有花括号语句2不是的if语句块,部分:

if (cond) 
    statement1; 
    statement2; 

然后语句2生效,无论是否COND是真的还是假的。 Java编译器不关心你的缩进。

要回答“我能做什么错”的问题:你在预先编写所有代码,并且只有在全部输入后才能使其工作。一次编写代码并且随时测试。一次编写大量代码只会导致大量的错误需要排序。

1

因为else与任何if都没有关联。

你有一个if这里,通过本身,它不会做任何事情:。

if (a+b>c&&b+c>a&&a+c>b); 

(注意分号这完全终止if块所以这是名副其实的if 。块)

如果你想要把这些代码随后的行放到if块,使用大括号:

if (a+b>c&&b+c>a&&a+c>b) { 
    System.out.println("The triangle with sides " + a + "," + b + ", and" + c + " is Scalene."); 
    if (a==b&&b==c) 
     System.out.println("The triangle with sides " + a + "," + b + ", and" + c + " is Equilateral"); 
    else // (a==b) || (a==c) || (b==c) 
     System.out.println("The triangle with sides " + a + "," + b + ", and" + c + " is Isoceles"); 
} 
else 
    System.out.println("There is no triangle with sides " + a + "," + b + ", and" + c); 

即使除了分号,只要您有多个语句放入代码块(例如if块或for循环)中,您就需要将这些语句与花括号组合在一起。

+0

我会更进一步,并建议使用大括号** ** if **和'else'块。 –

+0

@ Code-Apprentice:这更多的是个人喜好的问题,我不经常分享。该语言允许任何方式。 – David

+0

对于初学者来说,它有助于避免这样的错误。 –

1
if (a+b>c&&b+c>a&&a+c>b); 

这是一个noop。没有花括号的if只能包含一条指令。这条独特的指令是noop:;

使用时如果,而对于等