Search code examples
javaif-statementcompiler-errorscompareto

1. java ')' expected error + 2. 'else' without 'if' error


The error ')' expected is encountered on line 8; and the error 'else' without 'if' is found on line 9. This is only a part of the method. The beginning declares all needed variable (name1, name2, count), and states possible exceptions when reading the file. At this point, the program should already be reading the file in order to compare the names written in the file.

 while ( ! TextIO.eof() )
            do {
                name1.compareTo(name2);
                if (name1.equals(name2));
                count++;
            } while ( ! TextIO.eof() );





    if (count >= 0){
        System.out.println("You encountered" + count "identical names.");
    else
        System.out.println("There was no name encountered more than once.");
    }

Solution

  • Remove the ; at the end of the if statement. The ; ends the if statement.

    if (name1.equals(name2))
    count++;
    

    And add braces for if and else separately.

    if (count >= 0)
    {
        System.out.println("You encountered" + count + "identical names.");
    }
    else
    {
        System.out.println("There was no name encountered more than once.");
    }