简体   繁体   中英

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);
}

Nested for loop is itearting 5 times, summing 5 user inputs to variable hoursWorked . Point to all this is probably to count number of hours the user worked in that week (each iteration for each day of the week). Then get his salary by multiplying his hours by his pay per hour, and add it to total .

It's pretty straightforward, the only thing you may not understand is:

hoursWorked = hoursWorked + stdin.nextInt();

It translates to something like this:

new value of hoursWorked = old value of hoursWorked + userInput

It can also be written as:

hoursWorked += stdin.nextInt();

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).
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM