import java.util.*;
public class TestClass {
// These should (most likely) not be static
// Read up on what 'static' means
String name;
String gender;
String hairColor;
TestClass(String name, String gender, String hairColor){
this.name = name;
this.gender = gender;
this.hairColor = hairColor;
}
public static void main (String[]args) {
LinkedList<TestClass> linky = new LinkedList<TestClass>();
Scanner input = new Scanner(System.in);
System.out.println("Enter name ");
String name = input.nextLine();
System.out.println("Enter gender ");
String gender = input.nextLine();
System.out.println("Enter hair color ");
String hairColor = input.nextLine();
TestClass info = new TestClass(name, gender, hairColor);
linky.add(info);
}
}
Since linky is a LinkedList<TestClass> with generic type TestClass it can only hold objects of type TestClass so when you try to linky.add(name) it wont work
To print out the contents of the list you will need to iterate through the list and print each element, if the list contained Strings or something with an Overridden toString method, then you could simply call:
for(String str : linky){
System.out.println(str);
}
BUT this will not work because linky contains TestClasses. Therefor you could do this (but you should probably define geter methods for the fields of TestClass):
for(TestClass testClass : linky){
System.out.println("Name: " + testClass.name);
System.out.println("Gender: " + testClass.gender);
System.out.println("Hair Color: " + testClass.hairColor);
}
OR in TestClass you could override the toString method inherited from its superclass Object
// In TestClass
@Override
public String toString(){
// Format this however you like
return "Name :" + this.name + "; Gender: " + this.gender + "; Hair Color: " + this.hairColor;
}
Then all you would need to do is this:
for(TestClass testClass : linky){
// println(testClass) calls testClass.toString()
// giving you the formatted data from TestClass
System.out.println(testClass);
}
TestClassobjects contain no data! All data members arestatic. While you can add multipleTestClassobjects to the linked list, the objects are identical (ignoring reference identity).Cannot make a static reference to the non-static fieldon my lines that assign the user's input to the variable.