2016-02-19 57 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:;

使用時如果,而對於等