Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

[Java] Constructor Output Showing As Null

null constructor

  • Please log in to reply
1 reply to this topic

#1 900900

900900

    CC Newcomer

  • Member
  • PipPip
  • 10 posts
  • Learning:Java, C#, PHP, Lua

Posted 17 July 2012 - 07:27 PM

I have assignment where I need to create a class, 2 constructors, one to initialize all objects to 0 or empty strings. Then I have to create a new instance of the class in my main method and fill it with variables.

My problem is something isn't going right, because when I run it, this is the result:

Customer Number:0
First name:null
Last name:null
Address:null
Balance:0.0

So it's obviously not getting the input I give it, and using the default setting constructor as output. Which either tells me I did something wrong with creating my constructor - or I'm not filling the object with data correctly. (or even my display method is wrong?) What am I missing here? I've poured over stuff on the internet on Constructors but just can't seem to figure out what I'm doing wrong.

public class employee {

private int empID;
private String fname;
private String lname;
private String addr;
private String email;
private double salary;

employee() {
empID = 0;
fname = "";
lname = "";
addr = "";
email = "";
salary = 0;
}

employee(int id, String first, String last, String address, String eM, double sal) {
id = empID;
first = fname;
last = lname;
address = addr;
eM = email;
sal = salary;

}

public void display() {
System.out.println("Employee ID:" + empID);
System.out.println("First name:" + fname);
System.out.println("Last name:" + lname);
System.out.println("Address:" + addr);
System.out.println("Email:" + email);
System.out.println("Salary" + salary);
}





// Begin Main method
public static void main(String args[]) {


employee e1 = new employee(3,"bill","white","1311 River Lane","bill@bill.com",2000);


e1.display();



} // End Main Method
} // End Class

  • 0

#2 wim DC

wim DC

    Roar

  • Expert Member
  • PipPipPipPipPipPipPipPip
  • 2681 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Python

Posted 17 July 2012 - 10:27 PM

You swapped all the variables around:
id = empID;
first = fname;
last = lname;
address = addr;
eM = email;
sal = salary;

what's on the left should be on the right and vica versa.

Usually parameters like that have the same name as the class variabel:
employee(int empID, String fname, String lname, String addr, String email, double salary) {
  this.empID = empID;
  this.fname = fname;
  this.lname = lname;
  this.addr = addr; 
  this.email = email;
  this.salary = salary;
}
Even though you don't HAVE to of course.
  • 0





Also tagged with one or more of these keywords: null, constructor

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download