Reputation: 41
In the following code the &&
within the if else statement is giving a syntax error and i'm unsure how to solve it. Can anyone offer a solution?
//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.");
}
}
Upvotes: 3
Views: 203
Reputation: 121998
Correct syntax is
if (age>=18 && goodCreditHistory){
}
Remove unnecessary parentheses. And also you need not to write
goodCreditHistory== true
since it is already a boolean
.
Upvotes: 6
Reputation: 1975
This is because of how you put the parentheses. The if
statement is composed of two parentheses already, so you have to write you statement as
if ((age>=18) && (goodCreditHistory == true))
instead of
if (age>=18) && (goodCreditHistory == true)
since the second part of your statement (&& (goodCreditHistory == true)
) is being parsed as if it was part of the if
body.
You may write this statement in a more concise way as
if(age >= 18 && goodCreditHistory)
the extra parentheses are not needed. == true
statement is also redundant.
Upvotes: 14
Reputation: 38345
In Java the entire condition for an if
statement has to be contained within parentheses, so it should be:
if ((age>=18) && (goodCreditHistory== true)) {
Upvotes: 2
Reputation: 7521
Put both statements in one set of parentheses:
if (age>=18 && goodCreditHistory== true) {
System.out.println("You have got a credit card!");
}
Upvotes: 1