Armando Frias Armando Frias - 2 months ago 10
Java Question

Can someone explain to me what is going on within this nested loop?

Someone please explain what is going on within the nested loop below. I'm having trouble understanding how it works.

int numberOfTimesheets;
int centsPerHour = 0;
int hoursWorked;
total = 0;
numberOfTimesheets = stdin.nextInt();

for(int i = 1; i <= numberOfTimesheets; i++){
hoursWorked = 0;
centsPerHour = stdin.nextInt();
for (int ii = 1; ii <= 5; ii++){
hoursWorked = hoursWorked + stdin.nextInt();
}
total = total + (hoursWorked * centsPerHour);
}

Answer

This is the code commented with what it is doing at each step:

//go through each time sheet
for(int i = 1; i <= numberOfTimesheets; i++){
    hoursWorked = 0; // reset the number of hours worked (presumably for that week).
    centsPerHour = stdin.nextInt(); //get the wage of the current timesheet

    //go through each day for the current timesheet
    for (int ii = 1; ii <= 5; ii++){
        hoursWorked = hoursWorked + stdin.nextInt(); //add up the number of hours worked in that week
    }
    total = total + (hoursWorked * centsPerHour); //add the amount of money made this week to their current total (salary).
}
Comments