2013-08-05 51 views
-2

以下代碼導致語法錯誤'else' without 'if'。 我也不能從if語句中刪除分號,因爲它也會給我一個錯誤,告訴我我缺少分號。如果沒有「if」錯誤,就得到'else',但我不知道如何

import java.util.Scanner; 

class cake { 
    public static void main(String[] args) { 
     byte age, height; 
     Scanner in = new Scanner(System.in); 

     System.out.println("How old are you?"); 
     age = in.nextByte(); 

     System.out.println("How tall are you?"); 
     height = in.nextByte(); 

     if (age >= 10) && (height >= 48); { 
      System.out.println("You can ride!");   
     } else { 
      System.out.println("You cannot ride!"); 
     } 
    } 
} 
+0

外部括號....如果((年齡> = 10)&&(高度> = 48)) –

+0

if(age> = 10)&&(height> = 48); =>;關閉語句 – Shlublu

回答

5

你需要把一切都在括號內

if ((age >= 10) && (height >= 48)) { 
+1

並在if後面加上分號 – Maroun

0

與此代碼

if ((age >= 10) && (height >= 48)) { 
     System.out.println("You can ride!");   
    } else { 
     System.out.println("You cannot ride!"); 
    } 
0

您已經後分號 ')' 取代你,如果--- else條件刪除分號。這是主要問題。

if (age >= 10) && (height >= 48); 
+0

並將所有內容放在括號中。 – Maroun

0

我建議你使用nextInt,而不是nextByte。還寫如if語句像if((age >= 10) && (height >= 48))

這應該解決您的問題!

+1

一個字節不會比int存儲更多的內存,特別是如果這個人不應該超過-128或+127? –

+0

是的!但是,如果你搞砸了if語句,也許更容易堅持int ..只是一個建議! – wea

+1

有一天,人的預期壽命將超過128年,您的代碼將失敗:) –

2

你需要做的

if ((age >= 10) && (height >= 48)) { 
     System.out.println("You can ride!");   
    } else { 
     System.out.println("You cannot ride!"); 
    } 

因爲(age>=10) && (height >= 48)需要表達的是在if塊充分評估。

9
if (age >= 10) && (height >= 48); 

看看你添加的這條線;在最後,如果陳述沒有適當的封閉。所以把這兩種說法都附在單句中並刪除;現在聲明成爲

if ((age >= 10) && (height >= 48)) { 

閱讀此鏈接:Semicolon at end of 'if' statement

0

更換

if (age >= 10) && (height >= 48) 

if ((age >= 10) && (height >= 48)) 
0

這裏()@第一個和最後的你如果條件

現在是工作的罰款。

import java.util.Scanner; 

class Cake { 
    public static void main(String[] args) { 
     byte age, height; 
     Scanner in = new Scanner(System.in); 

     System.out.println("How old are you?"); 
     age = in.nextByte(); 

     System.out.println("How tall are you?"); 
     height = in.nextByte(); 

     if ((age >= 10) && (height >= 48)) { 
      System.out.println("You can ride!");   
     } else { 
      System.out.println("You cannot ride!"); 
     } 
    } 
} 

但有一件事我要告訴你的是「你多高?會不會接受十進制數。

+0

我應該然後宣佈高度作爲一個浮動,是否正確? –

+0

是的,你也需要調用 in.nextFloat(); //用於接受浮點數 in.nextInt(); //用於接受int in.nextDouble(); //接受雙等... 這裏是掃描儀的文檔類 http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html –

相關問題