JAVA Else without if?

3.7k Views Asked by At

I have this code for an assignment. When I compile it, I get

grades.java:18: error: 'else' without 'if'
    else
    ^
1 error

Here is the code:

public class grades
{
    public static void main (String [] args)
    {
        int gradeone=75;
        int gradetwo=80;
        int testscore= ((gradeone + gradetwo)/2);
        char grade;
        System.out.println("\n" + "your test score is" + testscore);
        if(testscore >= 90 )
      grade='A';
    elseif(testscore >= 80 );
      grade='B';
    elseif(testscore >= 70 );
      grade='C';
    elseif(testscore >= 65 );
      grade='D';
    else
      grade='F';
    }
}
5

There are 5 best solutions below

0
Edward J Beckett On BEST ANSWER

As others have already mentioned the syntax is else if - mind the space.

Moreover, I highly recommend you stick to conventional coding style until you become more confident in your skills.

A) For now, use brace syntax when using blocks and statements. Your code will be more readable and you will be able to identify your syntax errors easier. Though technically not required, you will be challenged trying to determine local variables and method scope without braces.

    public static void main( String[] args ) {
    int gradeOne = 75, gradeTwo = 80, testScore = ( ( gradeOne + gradeTwo ) / 2 );
    char grade;

    if( testScore >= 90 ) {
        grade = 'A';
    } else if( testScore >= 80 ) {
        grade = 'B';
    } else if( testScore >= 70 ) {
        grade = 'C';
    } else if( testScore >= 65 ) {
        grade = 'D';
    } else {
        grade = 'F';
    }
    System.out.println( "\n" + "your test score is: " + testScore );
}

B) When your uncertain about the syntax refer to the JLS for answers ...

1
Mordechai On

Remove the semi-colon after else if. This kind of bug happens because of the empty statement, it will execute the semi-colon if the condition meets, then execute the other code (grade = 'B';) w/o any evaluation, this will separate the if of the else

0
Martin On

else if instenad of elseif and you shouldn't have ; at the end of the else if lines.

0
AlexR On

Java does not have operator elseif. You have to write else if instead. So, java compiler is confused with your code and cannot find relevant if to your else.

1
Ramesh Karna On

put "else if" in place of elseif and remove the commas after the if expression. then your code becomes same as below which run perfectly :)

public class check {
    public static void main (String [] 
        int gradeone=75;
        int gradetwo=80;
        int testscore= ((gradeone + gradetwo)/2);
        char grade;
        System.out.println("\n" + "your test score is" + testscore);
        if(testscore >= 90 )
            grade='A';
        else if(testscore >= 80 )
            grade='B';
        else if(testscore >= 70 )
            grade='C';
        else if(testscore >= 65 )
            grade='D';
        else
            grade='F';    
}