Else without if error: I dont understand why java

2019-08-17 08:49发布

问题:

This question already has an answer here:

  • Error: 'else' without 'if' 3 answers

At line 53 it is giving me an error of else without if. I clearly have an if statement, but i don't know what i'm doing wrong to make java not recognize it. I've tried moving around the braces and nothing is working.

import java.util.Scanner;
import java.text.DecimalFormat;

public class Quiz6
{

    public static void displayInfo()
    {
        System.out.println(
                            "\n\tAuthor: Allen Watson \n" +
                            "\tClass: \tCSCI 1250-001 \n" +
                            "\tDate: \t10/09/2013 \n" +
                            "\tLab: \tQuiz6 \n");
    }

    public static double calculatePay(int hourWorked, double hourlyRate)
    {
        double dPay;
        dPay = (hourWorked * hourlyRate);
        return dPay;
    }

    public static void main(String[] args)
    {
        Scanner Keyboard = new Scanner(System.in);
        DecimalFormat dfMoney = new DecimalFormat("$#,##0.00");
        String strName;
        int iCount;
        int iDaysWorked;
        int iTotalHoursWorked;
        int iSingleDayHours;
        double dHourlyRate;
        final byte WEEK = 7;

        displayInfo();

        System.out.print("\tWhat is your name: ");
        strName = Keyboard.nextLine();
        System.out.print("\n\tHow many days did you work this week: ");
        iDaysWorked = Keyboard.nextByte();
        System.out.print("\n\tHow much do you make an hour: ");
        dHourlyRate = Keyboard.nextDouble();

        if(dDaysWorked <= WEEK);
        {
            for(iCount = 1; iCount <= iDaysWorked ; iCount++)
            {
                System.out.print("\tHow many hours did you work on the day"+iCount+":");
                iSingleDayHours = Keyboard.nextInt();
                iSingleDayHours += iTotalHoursWorked;
            }   
        }
        else
        {
            bDaysWorked = 0;
            System.out.print("A week can only have seven days");
        }

        calculatePay(iTotalHoursWorked,dHourlyRate);

        System.out.print("Hello "+strName+", you worked a total of "+iTotalHoursWorked+" hours over "+iDaysWorked+" days.");
        System.out.print("\nWith am hourly rate of "+dfMoney(dHourlyRate)+" you made "+dfMoney(dPay)+".");

    }
}

回答1:

Here's the problem:

if(dDaysWorked <= WEEK); // remove the ;

That trailing ; is making Java believe that the if statement is finished, and the {} block after it is outside the if condition, consequently the else part has no matching if preceding it.

This is a rather frequent bug, and a hard one to spot. If it weren't for the else block, the code would have compiled correctly, but it would have been wrong. Bottom line: never, ever put a ; in the opening line of an if, for or while statement.



回答2:

if(dDaysWorked <= WEEK); - remove last ;