在下面的代碼&&
內的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.");
}
}
這是多餘的寫'== TRUE'在'if'語句。可能發生的問題是錯誤地分配而不是比較。所以,只要寫'if(something)'而不是'if(something == true)''。 – Maroun
圍繞第一個條件,即(年齡> = 18)沒有括號的答案利用了算子優先級。看看http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html。 > =具有比&&更高的優先級,所以即使沒有括號,也會先評估它。 – rajah9