New to Java!
I have created a class that has constructors for various fields. However, when I try and print the fields, I recieve "null" as the output. Please help me understand why. Here is the class:`
public class User {
//All relevant information to identify each user.
private String FirstName;
private String LastName;
private String Email;
private long PhoneNum;
private long CardNum;
//Build Constructors for User info.
public User(String Fname, String Lname, String Mail, long num, long card)
{
Fname=FirstName;
Lname=LastName;
Mail=Email;
num=PhoneNum;
card=CardNum;
}
//Method to set FirstName.
public void setFirstName (String Fname)
{
FirstName=Fname;
}
//Method to get FirstName.
public String getFirstName()
{
return FirstName;
}
//Method to set LastName.
public void setLastName (String Lname)
{
LastName=Lname;
}
//Method to get Lastname.
public String getLastname()
{
return LastName;
}
//Method to set email.
public void setEmail (String Mail)
{
Email=Mail;
}
//Method to get email.
public String getEmail()
{
return Email;
}
//Method to set phonenumber.
public void setPhoneNum(long num)
{
PhoneNum=num;
}
//Method to get phonenumber.
public long getPhoneNum()
{
return PhoneNum;
}
//Method to set credit card number.
public void setCardNum(long card)
`enter code here`{
CardNum=card;
}
// Method to get credit card number.
public long getCardNum()
{
return CardNum;
}
Now when I run this code, I receive "null":
public class UserDemo {
public static void main(String[] args)
{
String first="Matt";
String last="Burns";
String email="mburns267#yahoo.com";
long phone=333;
long card=222;
User Matt=new User(first,last,email,phone,card);
System.out.print(Matt.getLastname());
}
What am I doing wrong? Thank you in advance!
`
Is the other way around, instead of:
public User(String Fname, String Lname, String Mail, long num, long card){
Fname=FirstName;
Lname=LastName;
Mail=Email;
num=PhoneNum;
card=CardNum;
}
it should be:
public User(String Fname, String Lname, String Mail, long num, long card){
FirstName = Fname;
LastName = Lname;
Email = Mail;
PhoneNum = num;
CardNum = card;
}
To avoid this kind of thing you can use the this keyword. Here is an example:
String firstName;
public Constructor(String firstName){
this.firstName = firstName;
}
You have your constructor assignments the wrong way:
public User(String Fname, String Lname, String Mail, long num, long card)
{
// this refers to the current object being constructed
this.FirstName = Fname;
this.LastName = Lname;
this.Email = Mail;
this.PhoneNum = num;
this.CardNum = card;
}
Java constructor objects should be created like so:
public User(String Fname, String Lname)
{
this.firstName = Fname;
//keyword 'this' refers to the new object, so the new object's Fname would equal the firstName place below
this.lastName = Lname; //same as above
}
To create a new User, use this code:
User Matt = new("Matt", "Burns"); //Creates a new User Matt, with firstName "Matt" and lastName "Burns"
System.out.println(Matt.getfirstName()); //prints User Matt's firstName to the console.
Related
class Client {
public static void AddList(User user) {
}
static class User {
public String name;
public String age;
public String mail;
public User(String name, String age, String mail) {
this.name = name;
this.age = age;
this.mail = mail;
}
}
static ArrayList<Object> list = new ArrayList<>();
public void AddList(String name, String age, String mail) {
list.add(new User(name, age, mail));
}
}
public class Main {
public static void main(String[] args) {
System.out.println("Give info plz");
Scanner scanner = new Scanner(System.in);
String name = scanner.nextLine();
String age = scanner.nextLine();
String mail = scanner.nextLine();
Client.AddList(new Client.User(name,age,mail));
Client.list.add("dqdqd");
Client.list.add(1);
for(Object s : Client.list) {
System.out.println(s);
}
}
}
This is a line when it doesn’t work for me, the program should take values and put them in an Arraylist, in general, the program should work like a database, take values and put them in an Arraylist, but this line does not work for me, please help.
public void AddList(String name, String age, String mail) {
list.add(new User(name, age, mail));
}
}
enter image description here as you can see in the screenshot, the data entered is simply lost
This is because you haven't implemented the AddList(User user) method. You've only implemented the AddList(String name, String age, String mail)
public static void AddList(User user) {
}
Should be something like
public static void AddList(User user) {
list.add(user);
}
To print the object you will need to create a toString() method for your object.
static class User {
public String name;
public String age;
public String mail;
public User(String name, String age, String mail) {
this.name = name;
this.age = age;
this.mail = mail;
}
public String toString() {
return name + ", " + age + ", " + mail;
}
}
You have two AddList(User) methods - one is a class method (i.e. static) and the other is an instance method. You are calling the class method which has no body. Since you never instantiate an instance of Client there is no purpose to the instance method. Move the body from the instance method to the class method and remove the instance method.
class Client {
static ArrayList<Object> list = new ArrayList<>();
public static void AddList(User user) {
list.add(new User(name, age, mail));
}
static class User {
public String name;
public String age;
public String mail;
public User(String name, String age, String mail) {
this.name = name;
this.age = age;
this.mail = mail;
}
}
}
There is a compliation error stating that class name is already define i can't find the way to resolve it
further the class name are declared only once and can't find the place where the things are going wrong
package practo;
import java.io.*;
import java.lang.*;
import java.util.*;
#SuppressWarnings("unused")
class Customer /* compilation error occurs here */
{
private int id;
private String name;
private String email;
private String address;
void setid(int id)
{
this.id=id;
}
int getid()
{
return id;
}
void setname(String name)
{
this.name=name;
}
String getname()
{
return name;
}
void setemail(String email)
{
this.email=email;
}
String getemail()
{
return email;
}
void setaddress(String address)
{
this.address=address;
}
String getaddress()
{
return address;
}
class PhoneNumber
{
private String phoneNumber;
private String heldFromDate;
private String heldToDate;
void setphoneNumber(String phoneNumber)
{
this.phoneNumber=phoneNumber;
}
String getphoneNumber()
{
return phoneNumber;
}
void setheldToDate(String heldToDate)
{
this.heldToDate=heldToDate;
}
String getheldToDate()
{
return heldToDate;
}
public String getHeldFromDate() {
return heldFromDate;
}
public void setHeldFromDate(String heldFromDate) {
this.heldFromDate = heldFromDate;
}
class NumberType
{
private String code;
private String description;
void setcode(String code)
{
this.code=code;
}
void setdescription(String description)
{
this.description=description;
}
String getcode()
{
return code;
}
String getdescription()
{
return description;
}
}
}
}
class x1
{
public void main(String args[])
{
#SuppressWarnings("resource")
Scanner s=new Scanner(System.in);
Customer c=new Customer();
Customer.PhoneNumber p=c.new PhoneNumber();
Customer.PhoneNumber.NumberType n=p.new NumberType();
System.out.println("Enter the customer details");
System.out.println("Enter the id :");
int id=s.nextInt();
c.setid(id);
System.out.println(c.getid());
System.out.println("Enter the name :");
String name=s.nextLine();
c.setname(name);
System.out.println(c.getname());
System.out.println("Enter the email :");
String email=s.nextLine();
c.setemail(email);
System.out.println(c.getemail());
System.out.println("Enter the address :");
String address=s.nextLine();
c.setaddress(address);
System.out.println(c.getaddress());
System.out.println("Enter the customer contact details");
System.out.println("Enter the phone number :");
String phoneNumber=s.nextLine();
p.setphoneNumber(phoneNumber);
System.out.println(p.getphoneNumber());
System.out.println("Enter the held from date (dd/MM/yyyy) :");
String heldFromDate=s.next();
p.setHeldFromDate(heldFromDate);
System.out.println(p.getHeldFromDate());
System.out.println("Enter the held to date (dd/MM/yyyy) :");
String heldToDate=s.next();
p.setheldToDate(heldToDate);
System.out.println(p.getheldToDate());
System.out.println("Enter number type code :");
String code=s.next();
n.setcode(code);
System.out.println(n.getcode());
System.out.println("Enter number type description");
String description=s.next();
n.setdescription(description);
System.out.println(n.getdescription());
}
}
Your class does not give me any compilation error. You might try making the class public i.e. public class Customer and file name having the name Customer.java. It may happen that the package practo already contains a class named Customer.
Can you please verify Customer class is not duplicate ? If it is not there, can you choose Clean from the Project menu, it might fix these errors.
Sometime eclipse trouble us.
Lots of recommendations for improvement:
Open public class per file, and a file for each class. Your arrangement is confusing.
Learn and follow the Java coding standards.
Using a Date for a date instead of a String is a better design, especially with JDK 8 and the java.time package.
Learn JUnit instead of that x1.main.
These are examples of how your classes should look.
Customer.java
package practo;
/**
* Created by Michael
* Creation date 5/29/2016.
* #link https://stackoverflow.com/questions/37511168/it-show-the-error-that-customer-is-already-defined-please-let-me-know-whats-wron
*/
public class Customer {
private int id;
private String name;
private String email;
private String address;
public Customer() {
this(0, "", "", "");
}
public Customer(int id, String name, String email, String address) {
this.id = id;
this.name = name;
this.email = email;
this.address = address;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
PhoneNumber.java:
package practo;
/**
* Created by Michael
* Creation date 5/29/2016.
* #link https://stackoverflow.com/questions/37511168/it-show-the-error-that-customer-is-already-defined-please-let-me-know-whats-wron
*/
public class PhoneNumber {
private String phoneNumber;
private String heldFromDate; // Bad design. This ought to be a Date, not a String
private String heldToDate; // Bad design. This ought to be a Date, not a String
public PhoneNumber() {
this("", "", "");
}
public PhoneNumber(String phoneNumber, String heldFromDate, String heldToDate) {
this.phoneNumber = phoneNumber;
this.heldFromDate = heldFromDate;
this.heldToDate = heldToDate;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getHeldFromDate() {
return heldFromDate;
}
public void setHeldFromDate(String heldFromDate) {
this.heldFromDate = heldFromDate;
}
public String getHeldToDate() {
return heldToDate;
}
public void setHeldToDate(String heldToDate) {
this.heldToDate = heldToDate;
}
}
Check if you have another class called Customer in the package practo. That would cause a name conflict.
Summary:
New to Java, tried looking through other posts but didn't find an answer. I'm learning inheritance and have an AddressBook class extended by a Runner class. When I write a program to test the inheritance I create a Runner object. If I get the first String parameter it returns fine but when I attempt to get the second String parameter it returns null.
Question:
Why is the second parameter returning null?
package Assignment_1;
//Begin Class Definition
public class AddressBook {
// Member variables
private String businessPhone;
private String cellPhone;
private String facebookId;
private String firstName;
private String homeAddress;
private String homePhone;
private String lastName;
private String middleName;
private String personalWebSite;
private String skypeId;
//Constructors
public AddressBook (String firstName, String middleName, String lastName, String homeAddress, String businessPhone, String homePhone, String cellPhone, String skypeId, String facebookId, String personalWebSite) {
this.firstName = firstName;
this.middleName = middleName;
this.lastName = lastName;
this.homeAddress = homeAddress;
this.businessPhone = businessPhone;
this.homePhone = homePhone;
this.cellPhone = cellPhone;
this.skypeId = skypeId;
this.facebookId = facebookId;
this.personalWebSite = personalWebSite;
}
public AddressBook (String firstName) {
this.firstName = firstName;
}
public AddressBook(String firstName, String middleName) {
this.firstName = firstName;
this.middleName = middleName;
}
public AddressBook (String firstName, String middleName, String lastName) {
this.firstName = firstName;
this.middleName = middleName;
this.lastName = lastName;
}
// Getters and setters
public String getFirstName() {
return firstName;
}
public String getMiddleName() {
return middleName;
}
public String getLastName() {
return lastName;
}
public String getHomeAddress() {
return homeAddress;
}
public String getBusinessPhone() {
return businessPhone;
}
public String getHomePhone() {
return homePhone;
}
public String getCellPhone() {
return cellPhone;
}
public String getSkypeId() {
return skypeId;
}
public String getFacebookId() {
return facebookId;
}
public String getPersonalWebsite() {
return personalWebSite;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setHomeAddress(String homeAddress) {
this.homeAddress = homeAddress;
}
public void setBusinessPhone(String businessPhone) {
this.businessPhone = businessPhone;
}
public void setHomePhone(String homePhone) {
this.homePhone = homePhone;
}
public void setCellPhone(String cellPhone) {
this.cellPhone = cellPhone;
}
public void setSkypeId(String skypeId) {
this.skypeId = skypeId;
}
public void setFacebookId(String facebookId) {
this.facebookId = facebookId;
}
public void setPersonalWebSite(String personalWebSite) {
this.personalWebSite = personalWebSite;
}
// Public methods
public static void compareNames(String name1, String name2) {
if(name1.equals(name2)) {
System.out.println(name1);
System.out.println(name2);
System.out.println("The names are the same.");
} else {
System.out.println(name1);
System.out.println(name2);
System.out.println("The names appear to be different.");
}
}
************************************************************
package Assignment_1;
public class BanffMarathonRunner extends AddressBook {
// Member variables
private int time;
private int years;
// Constructors
public BanffMarathonRunner(String firstName, String lastName, int min, int yr) {
super(firstName, lastName);
time = min;
years = yr;
}
// Getters and Setters
public int getTime() {
return time;
}
public void setTime(int time) {
this.time = time;
}
public int getYears() {
return years;
}
public void setYears(int years) {
this.years = years;
}
}
************************************************************
package Assignment_1;
import Assignment_1.BanffMarathonRunner;
public class TestBanffMarathonRunner {
public static void main(String[] args) {
BanffMarathonRunner r1 = new BanffMarathonRunner("Elena", "Brandon", 341, 1);
System.out.print(r1.getLastName());
}
}
}
Because lastName is null.
You are calling AddressBook(String firstName, String middleName)
and setting the middleName, not the lastName.
BanffMarathonRunner r1 = new BanffMarathonRunner("Elena", "Brandon", 341, 1);
calls:
// firstName = "Elena"
// lastName = "Brandon"
// min = 341
// yr = 1
public BanffMarathonRunner(String firstName, String lastName, int min, int yr) {
super(firstName, lastName);
// ...
}
which calls via super(...):
// firstName = "Elena"
// middleName = "Brandon" <-- here is your issue
public AddressBook(String firstName, String middleName) {
this.firstName = firstName;
this.middleName = middleName;
}
Brandon is set in AddressBook#middleName instead of AddressBook#lastName.
Your problem is in the BanffMarathonRunner.java:
in the constructor when you are calling the
super(firstName, lastName);
Actually by the call above the super class constructor with two parameter is being called, and that constructor is the one which set the middleName not the lastName.
I think you are confused because of the lastName variable name, which is passed to the constructor with two argument and that constructor use the second argument to set the middleName.
Good Luck.
Please help me find errors from this code. I'm still new and I don't know if this is correct or not.
I do have one error.
This is the error:
constructor Person in class Person cannot be applied to given types;
super();
^
required: String,String,String
found: no arguments
reason: actual and formal argument lists differ in length
This is my code:
import java.util.*;
public class Person {
//Data fields
private String lastName;
private String middleInitial;
private String firstName;
//Constructors
public Person(String lastName, String middleInitial, String firstName) {
this.lastName = lastName;
this.middleInitial = middleInitial;
this.lastName = lastName;
}
//Accessor methods
public String getlastName() {
return lastName;
}
public String getmiddleInitial() {
return middleInitial;
}
public String getfirstName() {
return firstName;
}
//Mutator methods
public void setlastName(String lastName) {
lastName = lastName;
}
public void setmiddleInitial(String middleInitial) {
middleInitial = middleInitial;
}
public void setfirstName(String firstName) {
firstName = firstName;
}
public String getName() {
String studentName = this.lastName + ", " + this.firstName +
this.middleInitial + ".";
return studentName;
}
} //end Person class
class Address {
//Data fields
private String streetName;
private int zipCode;
private String state;
private String country;
//Constructors
public Address(String streetName, int zipCode, String state,
String country) {
this.streetName = streetName;
this.zipCode = zipCode;
this.state = state;
this.country = country;
}
//Accessor methods
public String getstreetName() {
return streetName;
}
public int getzipCode() {
return zipCode;
}
public String getstate() {
return state;
}
public String getcountry() {
return country;
}
//Mutator methods
public void setstreetName(String streetName) {
streetName = streetName;
}
public void setzipCode(int zipCode) {
zipCode = zipCode;
//Integer.toString(zipCode);
}
public void setstate(String state) {
state = state;
}
public void setcountry(String country) {
country = country;
}
public String getAddress() {
String studentAddress = streetName + "\n" + state + ", " + country +
"\n" + zipCode;
return studentAddress;
}
} //end Address class
class Student extends Person {
private String dateOfBirth;
//Constructors
public Student (String studentName, String dateOfBirth) {
super();
dateOfBirth = dateOfBirth;
}
//Accessor methods
public String getdateOfBirth() {
return dateOfBirth;
}
//Mutator methods
public void setdateOfBirth() {
this.dateOfBirth = dateOfBirth;
}
public String toString() {
return ("Date of Birth: " + dateOfBirth);
}
} //end Student subclass
Edited: If I do so for both the Person and Address class. I can only have three-arg constructors. How can I call a one-arg constructor?
For example, I have
public Student (String firstName, String lastName, String middleInitial, String dateOfBirth) {
super(firstName, lastName, middleInitial); and
public Student (String streetName, String state, String country) {
super(streetName, state, country);
How can I get zipcode separately?
Class Person has a constructor, therefore the default no-arg constructor is not created for you. Therefore you can't call super() in Student's constructor, you have to call super(lastName, middleInitial, firstName);.
Or you could create a new Person no-arg constuctor.
Try this
In student class
public Student ( String lastName, String middleInitial, String firstName,String studentName, String dateOfBirth) {
super( lastName, middleInitial,firstName);
this.dateOfBirth = dateOfBirth;
}
Or
In Person class create no arg consructor. Eg:
public Person(){}
Person Class has a constructor with arguments. So default constructor will not be created. So you have to pass 3 String parameters in super(3 String parameters) or you have to create a constructor which does not take any parameter in person class.
Recently I am doing a coding exercises I need to make my project , and so far I am practicing it with the code below what I want to ask is that, is this a has a relationship? am I doing the right practice? look at my code, sorry for my bad english
public class Personal {
private String firstName;
private String middleInitial;
private String lastName;
private int age;
public Personal(String firstName,String middleInitial , String lastName , int age){
setFirstName(firstName);
setMiddleInitial(middleInitial);
setLastName(lastName);
setAge(age);
}
public void setFirstName(String firstName){
this.firstName = firstName;
}
public String getFirstName(){
return firstName;
}
public void setMiddleInitial(String middleInitial){
this.middleInitial = middleInitial;
}
public String getMiddleInitial(){
return middleInitial;
}
public void setLastName(String lastName){
this.lastName = lastName;
}
public String getLastName(){
return lastName;
}
public void setAge(int age){
this.age = age;
}
public int getAge(){
return age;
}
public String toString(){
return String.format("First Name: "+getFirstName()+"\nMiddle Initial: "+getMiddleInitial()+
"\nLast Name: "+getLastName()+"\nAge: "+getAge());
}
}
Contact Class
public class Contact {
private String address;
private String email;
private String contactNumber;
public Contact(String address,String contactNumber, String email){
setAddress(address);
setContactNumber(contactNumber);
setEmail(email);
}
public void setAddress(String address){
this.address = address;
}
public String getAddress(){
return address;
}
public void setEmail(String email){
this.email = email;
}
public String getEmail(){
return email;
}
public void setContactNumber(String contactNumber){
this.contactNumber = contactNumber;
}
public String getContactNumber(){
return contactNumber;
}
public String toString(){
return String.format("Address: "+getAddress()+"\nContact Number: "+getContactNumber()+
"\nEmail Address: "+getEmail());
}
}
Employee Class
public class Employee {
private Personal personal;
private Contact contact;
public Employee(Personal personal, Contact contact){
this.personal = personal;
this.contact = contact;
}
public void setFirstName(String firstName){
this.personal.setFirstName(firstName);
}
public String toString(){
return String.format(personal.toString()+contact.toString());
}
}
And the Test class
public class TestClass {
public static void main(String[] args){
Personal personalHerp = new Personal("John","M","Doe",18);
Contact contactHerp = new Contact("88 Herp Derp St U mad New york","724-15-70","fido.com");
Employee employeeHerp = new Employee(personalHerp,contactHerp);
System.out.println(employeeHerp);
}
}
Well, since Employee doesn't extend Personal it has a Personal and a Contact.
I guess you'd rather like Employee to be a Personal and thus it should look like this:
public class Employee extends Personal {
private Contact contact;
...
}
So to summarize:
is-a means a class/object extends another class or implements an interface, i.e. A is-a B if A extends B or A implements B
has-a means that a class/object has a variable of that type, like Contact contact in your Employee class, which means Employee has-a contact.
Yes, this is a "has-a" relationship (exactly as we discussed in your other question).