2016-02-15 93 views
1

我是新來的java,我無法弄清楚爲什麼這裏有語法錯誤。我已經複製並粘貼了代碼,並且我評論了錯誤的位置。令牌上的語法錯誤「else」,刪除這個令牌

import java.util.Scanner; 
public class CountryDetails { 
    public static void main(String [] args) { 
    Scanner input=new Scanner(System.in); 
    System.out.println("Enter any of the following integers to see details of the corresponding country:(1, 36, 57, 94, 250, 269, 354, 376, 597, 678, 962, 992)"); 
    //prompt reader to enter a number 
    int code=input.nextInt(); 

    int x; 
    x=input.nextInt(); 
    if ((x!=1)&&(x!=36)&&(x!=57)&&(x!=94)&&(x!=250)&&(x!=269)&&(x!=354)&&(x!=376)&&(x!=597)&&(x!=678)&&(x!=962)&&(x!=992)); { 
     System.out.println("You did not enter one of the possible integers."); 
    } 

    else if (x==1) { //error is here 
     System.out.println("Enter amount in US dollars:"); //prompt reader to enter US dollars 
     double dollars = input.nextDouble(); //reading input 
     double exchangeRate= dollars*45.72; 

     //display results 
     System.out.println ("1 is the Country Calling Code for the Dominican Republic, which is located in the Americas"); 
     System.out.println (+dollars+ " is equivalent to " +exchangeRate+ "Dominican Pesos."); 
    } 

謝謝!

+2

你可能要考慮創建一個整數列表(例如'名單國家= Arrays.asList(36,57,94/*等* /) ;'),這將允許你在你的消息中簡化條件爲'if(!countries.contains(x)){',並且只使用'countries.toString()'(例如'System.out.println(「輸入以下任何一個......「+ countries +」:「)')。 –

回答

3

通過你的long if語句,最後去掉分號。

// The semicolon at the end of this line 
if ((x!=1)&&(x!=36)&&(x!=57)&&(x!=94)&&(x!=250)&&(x!=269)&&(x!=354)&&(x!=376)&&(x!=597)&&(x!=678)&&(x!=962)&&(x!=992)); { 
    System.out.println("You did not enter one of the possible integers."); 
} 
1

這裏是ifif-else報表java如何工作的好tutorial。在java中考慮以下兩種情況。

案例#1

if (boolean-expression) 
    statement 

案例#2

if (boolean-expression-1) 
{ 
     statement-1 
     statement-11 
     statement-111 
} 
else 
{ 
     statement-2 
     statement-22 
} 

java每個語句與;結束。而一個;本身是有效的,這是一個空話,什麼都不做。在你的代碼,你的意思是寫它有看起來像案例2if-else條件,但由於錯誤;java把它當作案例1,當它遇到的關鍵字else它拋出一個錯誤。

在您的示例代碼中,java編譯器認爲if條件結尾處的分號爲空語句。但else總是需要與if聲明一起。更改if條件除去;看起來像下面 -

if ((x!=1)&&(x!=36)&&(x!=57)&&(x!=94)&&(x!=250)&&(x!=269)&&(x!=354)&&(x!=376)&&(x!=597)&&(x!=678)&&(x!=962)&&(x!=992)) { 
     System.out.println("You did not enter one of the possible integers."); 
    } 
相關問題