import java.util.*;
public class TestClass {
static String name;
static String gender;
static String hairColor;
TestClass(String name, String gender, String hairColor){
this.name=name;
this.gender=gender;
this.hairColor=hairColor;
}
public static void main (String[]args) {
TestClass info = new TestClass(name, gender, hairColor);
LinkedList<TestClass> linky = new LinkedList<TestClass>();
Scanner input = new Scanner(System.in);
System.out.println("Enter name ");
name=input.nextLine();
System.out.println("Enter gender ");
gender=input.nextLine();
System.out.println("Enter hair color ");
hairColor=input.nextLine();
}
}
我想将用户输入添加到链接列表中,但我不知道该怎么做。我尝试使用 linky.add(name);
但这会出错。如何将输入添加到链表中?
最佳答案
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);
}
}
因为 linky 是一个 LinkedList<TestClass>
使用通用类型 TestClass
它只能容纳 TestClass
类型的对象所以当你尝试 linky.add(name)
它不会工作
要打印出列表的内容,您需要遍历列表并打印每个元素,如果列表包含String
。 s 或带有 Overridden toString
的东西方法,那么你可以简单地调用:
for(String str : linky){
System.out.println(str);
}
但是这不会起作用因为linky
包含 TestClass
es。因此你可以这样做(但你可能应该为 TestClass 的字段定义 get
er 方法):
for(TestClass testClass : linky){
System.out.println("Name: " + testClass.name);
System.out.println("Gender: " + testClass.gender);
System.out.println("Hair Color: " + testClass.hairColor);
}
或 TestClass
你可以覆盖 toString
从其父类(super class)继承的方法 Object
// In TestClass
@Override
public String toString(){
// Format this however you like
return "Name :" + this.name + "; Gender: " + this.gender + "; Hair Color: " + this.hairColor;
}
那么你需要做的就是:
for(TestClass testClass : linky){
// println(testClass) calls testClass.toString()
// giving you the formatted data from TestClass
System.out.println(testClass);
}
关于java - 我怎样才能让这个程序将用户输入添加到我的链接列表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47639874/