对于循环,整数值不更新

时间:2016-02-29 19:40:34

标签: java for-loop

薪水的值未在for循环中更新。如果我输入的薪水是17000,那么第一年的%是5%我得到17850的输出是正确的。然后循环再次返回,我再次输入例如5%,我再次得到17850的输出。我预计它会再增加5%来获得18742.5。

int n = Integer.parseInt(JOptionPane.showInputDialog("Please enter the amount of employees"));    
int yr = Integer.parseInt(JOptionPane.showInputDialog("Please enter the amount of years"));

for (int i = 1; i <=n; i ++) {
   double salary = Double.parseDouble(JOptionPane.showInputDialog("Please enter the salary for employee "+i));
   for (int y = 1; y <= yr; y++) {
      double percentage = Double.parseDouble(JOptionPane.showInputDialog("Please enter the percentage for year " +y));
      double perc =(salary * percentage / 100);
      double ann = perc + salary;
      JOptionPane.showMessageDialog(null, "Annual salary for employee " +i +" for the year " +y +" is €"+ann);
   } 
}

4 个答案:

答案 0 :(得分:1)

那是因为你没有每年更新薪水,所以每年的结果都是一样的。尝试每年更新薪水或将薪水保存在不同的变量中。

以下是对代码的修改:

int n = Integer.parseInt(JOptionPane.showInputDialog("Please enter the amount of employees"));    
int yr = Integer.parseInt(JOptionPane.showInputDialog("Please enter the amount of years"));

for (int i = 1; i <=n; i ++) {
   double salary = Double.parseDouble(JOptionPane.showInputDialog("Please enter the salary for employee "+i));
   for (int y = 1; y <= yr; y++) {
      double percentage = Double.parseDouble(JOptionPane.showInputDialog("Please enter the percentage for year " +y));
      double perc =(salary * percentage / 100);
      salary = perc + salary;
      JOptionPane.showMessageDialog(null, "Annual salary for employee " +i +" for the year " +y +" is €"+salary);
   } 
}

答案 1 :(得分:0)

您的salary未更新,因为从未在任何类型的累加器中使用...

你在这里定义:

double salary = Double.parseDouble(JOptionPane.showInputDialog("Please enter the salary for employee "+i));

之后你正在阅读它但从未写过它..

答案 2 :(得分:0)

代码中的修改很少:

{{1}}

答案 3 :(得分:0)

添加

salary=ann;

后:

  JOptionPane.showMessageDialog(null, "Annual salary for employee " +i +" for the year " +y +" is €"+ann);

修改后的代码:

int n = Integer.parseInt(JOptionPane.showInputDialog("Please enter the amount of employees"));    
int yr = Integer.parseInt(JOptionPane.showInputDialog("Please enter the amount of years"));

for (int i = 1; i <=n; i ++) {
   double salary = Double.parseDouble(JOptionPane.showInputDialog("Please enter the salary for employee "+i));
   for (int y = 1; y <= yr; y++) {
      double percentage = Double.parseDouble(JOptionPane.showInputDialog("Please enter the percentage for year " +y));
      double perc =(salary * percentage / 100);
      double ann = perc + salary;
      JOptionPane.showMessageDialog(null, "Annual salary for employee " +i +" for the year " +y +" is €"+ann);
      salary=ann;
   } 
}

希望这能得到你的解决方案。