【问题标题】:How to make a for-loop output proper values of an array from a method如何使for循环从方法中输出正确的数组值
【发布时间】:2016-08-16 14:55:41
【问题描述】:

我正在开发一个程序,该程序获取具有给定 ID 号的员工的工资率和小时数,将它们存储在数组中,并使用一种方法来确定员工的总工资,该方法也将存储在数组中。我的程序可以接受员工的工资率和小时数,但是当它输出员工 ID 和相应的总工资时,它会返回一组奇数字符,例如 [D@1909752.如何让程序正确输出给定员工的总工资?我认为问题出现在方法和将方法传递给最终的 for 循环之间,以及我的方法将 int 乘以 double 的事实,但我不知道从这里做什么。谢谢您的帮助。我的代码如下。

import java.util.Scanner;

class Payroll
{
   public static void main(String[] args)
   {
      int[] employeeId = {5658845, 4520125, 7895122, 8777541, 8451277, 1302850, 7580489};

      int[] hours = new int[7];

      double[] payRate = new double[7];

      for(int counter = 0; counter< 7; counter++)
      {
         Scanner keyboard = new Scanner(System.in);
         System.out.println("Enter the hours worked by employee #" + employeeId[counter]);
         hours[counter] = keyboard.nextInt();

            if (hours[counter] < 0)
            {
               System.out.println("Error: hours cannot be negative. The program will now close.");
               System.exit(0);
            }  
            else
            {
               continue;
            }
      } 

      for(int counter1 = 0; counter1< 7; counter1++)
      {
         Scanner keyboard = new Scanner(System.in);
         System.out.println("Enter the payrate of employee #" + employeeId[counter1]);
         payRate[counter1] = keyboard.nextDouble();

            if (payRate[counter1] < 6.0)
            {
               System.out.println("Error: payrate must be above 6.0. The program will now close.");
               System.exit(0);
            }  
            else
            {
               continue;
            }
      } 

      for (int counter2 = 0; counter2 < 7; counter2++)
      {
         System.out.println("The gross pay for employee #" + employeeId[counter2] + " is " + wages(employeeId, hours, payRate));
      }
   } 

   public static double[ ] wages(int[] employeeId, int[] hours, double[] payRate)
   {
      double[] wages = new double[7];

         for(int counter2 = 0; counter2< 7; counter2++)
         {
            wages[counter2] = hours[counter2] * payRate[counter2];
         }

      return wages;
   }

}

【问题讨论】:

  • 或许可以这样做:wages(employeeId, hours, payRate)[counter2]
  • 不,此时counter2 不可见。它是 wages 的本地地址。
  • 之所以有效,是因为我在 main 方法中也使用了counter2,以减少对我的困惑

标签: java arrays for-loop methods


【解决方案1】:

字符串[D@1909752toString() 的默认输出,应用于double 数组。在声明中

    System.out.println("The gross pay for employee #" + employeeId[counter2] + " is " + wages(employeeId, hours, payRate));

wages 方法返回一个由double 组成的数组,并且您告诉程序打印整个数组,而不是一个特定的元素。如果要打印所有七个元素,则需要使用循环或 lambda 单独打印每个元素。

【讨论】:

  • 或许可以这样做:wages(employeeId, hours, payRate)[counter2]
  • 感谢 Garrison 先生提供的信息和 jgitter,它工作得很好。谢谢大家!
猜你喜欢
  • 2021-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-01
  • 2023-04-01
  • 1970-01-01
  • 2018-07-30
  • 1970-01-01
相关资源
最近更新 更多