java将2D数组传递给构造函数
你能告诉我如何将2D数组传递给构造函数吗。我已经用值传递了数组,但我得到了错误的答案。在这里与我分享我的代码
package payroll;
import java.util.Scanner;
import javax.swing.*;
class Payroll
{
private String empID;
private String empName;
private int numOfHours;
private double hourlyRate;
private double totalPay;
public Payroll(){}
public Payroll(Object[][]emp, int scale)
{
for(int k=0;k<emp.length;k++)
{
this.empID = emp[k][l].toString();
this.empName = emp[k][l].toString();
this.numOfHours = Integer.parseInt(emp[k][l].toString());
this.hourlyRate = Integer.parseInt(emp[k][l].toString());
}
}
}
public String getID()
{
return empID;
}
public String getName()
{
return empName;
}
public int getNumOfHours()
{
return numOfHours;
}
public double getHourlyRate()
{
return hourlyRate;
}
public double gettoTotalPay()
{
return numOfHours * hourlyRate;
}
}
class Employer{
public static void main(String [] args)
{
String empId;
String empName;
String numOfHrs;
String hourlyRate;
Payroll emp1 = new Payroll();
Object [][]emp = new Object[1][1];
Scanner sc = new Scanner(System.in);
for(int i=0;i<emp.length;i++)
{ // start for loop
for(int j=0;j<emp[0].length;j++)
{
emp[i][j]= JOptionPane.showInputDialog(null,"Enter Employer ID");
if ( (emp[i][j].equals("")))
{
JOptionPane.showMessageDialog( null,"Employee ID Not Correct");
emp[i][j]= JOptionPane.showInputDialog(null,"Enter Employer ID");
}
emp[i][j] = JOptionPane.showInputDialog(null,"Enter Employer Name");
if(emp[i][j] == null )
{
JOptionPane.showMessageDialog(null,"Employee Name Cannot Be Empty");
emp[i][j] = JOptionPane.showInputDialog(null,"Enter Employer Name");
}
emp[i][j] = JOptionPane.showInputDialog(null,"Enter Number of Hours Worked on");
if(emp[i][j] == null )
{
JOptionPane.showMessageDialog(null,"Number of Hour Cannot be empty or more than 8");
emp[i][j] = Integer.parseInt(JOptionPane.showInputDialog(null,"Enter Number of Hours Worked on"));
}
emp[i][j] = JOptionPane.showInputDialog(null,"Enter Hourly Rate ");
if(emp[i][j] == null)
{
JOptionPane.showMessageDialog(null,"Number of Hourly Rate Cannot be empty or Minus Value");
hourlyRate = JOptionPane.showInputDialog(null,"Enter Hourly Rate ");
}
emp1 = new Payroll(emp,6 ); // this is the 2D array pass to Payroll Class
}//end inner for loop
}//end for loop
System.out.println("Employee Id:" +emp1.getID() );
System.out.println("Employee Name:" +emp1.getName() );
System.out.println("Employee Hours:" +emp1.getNumOfHours());
System.out.println("Employee Total Payment:" +emp1.gettoTotalPay() );
}
}
如果我插入
employe id:1
emaployee name : asd
employee num of hrs:1
employee hourly rate :100
但答案是
Employee Id:1
Employee Name:1
Employee Hours:1
Employee Total Payment:1.0
需要建议吗
# 1 楼答案
只需移除内部for循环并添加
三次在雇主班
现在它运行良好。正如你在评论中提到的那样,你之所以得到nullPointerException,是因为你不打算进入下一列,而是停留在第0列,因此你必须增加j
# 2 楼答案
我认为你没有在循环中增加Valrable l。你能用l++替换它吗。试着让我知道