-3

I am trying to create an array of three Strings with the values to the array elements being my name, my gender, and my email. Then writing a for loop to print out each element.

I am getting an error message saying: Error exists in current projects.

Help with what errors are in my code would be great.

public class arraytest {

private String firstName; 
private String gender; 
private String emailA;

/** Constructor */

public arraytest(String firstName, String gender, String emailA){
    this.firstName = firstName;
    this.gender = gender;
    this.emailA = emailA;
}


/** Getter - Returns the first name */ 

public String getFirstName() {
    return firstName;
}

/** Return the gender */ 

public String getGender() {
    return gender;
}

/** Returns the email address */

public String getEmailA() {
    return emailA;
}

public void setInfo(String firstName, String gender, String emailA){
    this.firstName = firstName;
    this.gender = gender;
    this.emailA = emailA;
}

public static void main (String[] args) {

String[] myInfo = new String[3];

arraytest test = new arraytest("Cameron","Male","cam@live.com");

myInfo[0] = test.firstName;
myInfo[1] = test.gender;
myInfo[2] = test.emailA;

for (int i=0; i<myInfo.length; i++) {

    System.out.println(myInfo[i]);

}

}

}

  • 3
    the array has only 1 element in it `arraytest` object, the rest are null. The default `toString()` for a type returns classname and hashcode of the object – Ramanlfc Dec 03 '18 at 22:15
  • You only assigned a value to `person[0]`, so why are you confused that `person[1]` and `person[2]` are null? – Andreas Dec 03 '18 at 22:21
  • Possible duplicate of [How do I print my Java object without getting “SomeType@2f92e0f4”?](https://stackoverflow.com/q/29140402/5221149) – Andreas Dec 03 '18 at 22:22
  • It’s unclear how you had intended that to work. You’ve created an array with space for 3 persons (3 `arraytest` objects), not 3 strings. – Ole V.V. Dec 03 '18 at 22:24

1 Answers1

0

You created a class which already contain this 3 elements. If you want to put them in an array, you can just do this:

public static void main (String[] args) {

arraytest[] person = new arraytest[3];

test = new arraytest("Cameron","Male","cam@live.com");

person[0] = test.firstName;
person[1] = test.gender;
person[2] = test.firstName;

for (int i=0; i<person.length; i++) {

    System.out.println(person[i]);

}

}

Exayls
  • 26
  • 3