有人可以向我解释这个嵌套循环中发生了什么吗?

时间:2016-09-25 19:09:30

标签: java

有人请解释下面嵌套循环中发生的事情。我无法理解它是如何工作的。

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

2 个答案:

答案 0 :(得分:1)

嵌套for循环迭代5次,将5个用户输入汇总到变量hoursWorked。指向所有这些可能是计算用户在该周工作的小时数(每周的每一天的每次迭代)。然后通过将他的小时数乘以他/小时的工资来获得他的工资,并将其添加到total

这很简单,你可能唯一不理解的是:

hoursWorked = hoursWorked + stdin.nextInt();

它转换为类似的东西:

new value of hoursWorked = old value of hoursWorked + userInput

它也可以写成:

hoursWorked += stdin.nextInt();

答案 1 :(得分:1)

这是代码评论它在每一步所做的事情:

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