我正在尝试获取某人的名字和姓氏,然后获取这两个 Strings
并将它们放入一个 ArrayList
一起。
我可以接受两个Strings
,但问题是我无法输出它们。
我有两个类(class),如下:
import java.util.ArrayList;
import java.util.Scanner;
public class TakeInName {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList<Names> studentNames = new ArrayList<Names>();
Names newName = new Names();
newName.firstName = scan.nextLine();
newName.lastName = scan.nextLine();
studentNames.add(newName);
Names item = studentNames.get(0);
System.out.print(item);
}
}
第二个:
public class Names {
String lastName;
String firstName;
}
我什至不确定我是否让第二类正确地能够用它做任何事情?也许这就是我的问题?
当我运行此代码时,得到的输出是:
Names@5c647e05
也许这就是内存位置?
感谢任何帮助,谢谢。
最佳答案
要获取您必须执行的操作
System.out.print(item.firstName+" "+item.lastName);
因为您正在获取 Names
对象。您获得的字符串(Names@5c647e05
) 是预期的。它是对象的字符串表示形式,其中 Name
是类,@
连接字符串的字符,以及 5c647e05
一些哈希码
回复评论。
代码是
Names newName1=new Names();
newName1.firstName = scan.nextLine();
newName1.lastName = scan.nextLine();
studentNames.add(newName1);
Names newName2=new Names(); //create new object for new name
newName2.firstName = scan.nextLine();
newName2.lastName = scan.nextLine();
studentNames.add(newName2);
Names item = studentNames.get(0);
System.out.print(item.firstName + " " + item.lastName);
Names item1 = studentNames.get(1);
System.out.print(item1.firstName + " " + item1.lastName);
关于java - 无法输出使用两个对象的ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29566833/