2013-10-08 74 views
3

在下面的代碼&&內的if else語句是給一個語法錯誤,我不知道該如何解決這個問題。誰能提供解決方案?麻煩與&&運營商

//Importing scanner 
import java.util.Scanner; 

public class Credithistory { 

    public static void main(String[] args) {    
     //Stating scanner gets its input from console 
     Scanner scanner= new Scanner (System.in);   
     //declaring int and boolean   
     int age; 
     boolean goodCreditHistory;   
     System.out.println("Please enter your age... "); 
     age= scanner.nextInt();   
     System.out.println("Do you have a good credit history (true or flase)?"); 
     goodCreditHistory= scanner.nextBoolean();   
     if (age>=18) && (goodCreditHistory== true){ // <-------------- Error 
      System.out.println("You have got a credit card!");    
     } else 
      System.out.println ("Sorry you are not eligible for a credit card."); 
    }  
} 
+4

這是多餘的寫'== TRUE'在'if'語句。可能發生的問題是錯誤地分配而不是比較。所以,只要寫'if(something)'而不是'if(something == true)''。 – Maroun

+1

圍繞第一個條件,即(年齡> = 18)沒有括號的答案利用了算子優先級。看看http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html。 > =具有比&&更高的優先級,所以即使沒有括號,也會先評估它。 – rajah9

回答

6

正確的語法是

if (age>=18 && goodCreditHistory){ 

} 

刪除不必要的括號中。而且你不需要寫

goodCreditHistory== true 

,因爲它已經是一個boolean

1

把兩個語句在一組括號:

if (age>=18 && goodCreditHistory== true) { 
    System.out.println("You have got a credit card!"); 
} 
14

這是因爲,你如何把括號。該if聲明是由兩個括號了,所以你必須寫你的語句作爲

if ((age>=18) && (goodCreditHistory == true)) 

,而不是

if (age>=18) && (goodCreditHistory == true) 

,因爲你的聲明的第二部分(&& (goodCreditHistory == true))被解析,如果它是if機構的一部分。

你可以更簡潔的方式寫這個語句

if(age >= 18 && goodCreditHistory) 

不需要額外的括號。 == true聲明也是多餘的。

+4

請注意,此處使用冗餘括號。 –

+0

@AdamArold是的,他們並不是真的有必要。 '== true'語句也是多餘的。我只是複製OP代碼。 – Mauren

+1

好的,編輯後+1。 –

2

在Java爲if語句整個條件需要含有括號內,所以它應該是:

if ((age>=18) && (goodCreditHistory== true)) {