我正在从Java教科书开发一个项目,我遇到了一个问题。我试图在数组中打印变量,但它不断打印变量位置(@hex代码)而不是实际变量...我相信我试图通过使用'for循环'正确打印数组。我在下面附上了我的代码......
import java.util.Scanner;
import java.util.Arrays;
import java.lang.String;
public class Main
{
public static void main(String[] args)
{
int ARRAY_LENGTH = 2;
Scanner in = new Scanner(System.in);
Person[] Persons;
Persons = new Person[ARRAY_LENGTH];
for (int i = 0; i < ARRAY_LENGTH; i++)
{
System.out.println("Enter a name to add to the array: ");
Persons[i] = new Person(in.next());
}
//Arrays.sort(Persons);
for (int i = 0; i < ARRAY_LENGTH; i++)
{
System.out.println(Persons[i]);
}
}
}
&安培;
public class Person implements Comparable<Person>
{
private String name;
public Person (String aName)
{
String name = aName;
}
public String getName()
{
return name;
}
public int compareTo(Person o)
{
Person other = (Person) o;
if (this.name.equals(o.name))
{
return 0;
}
if (this.name.compareTo(o.name) < 0)
{
return -1;
}
return 1;
}
}
感谢任何和所有指导。谢谢!
答案 0 :(得分:5)
您需要在<{1}}课程中覆盖 toString
方法。
Person
public class Person implements Comparable<Person>
{
private String name;
public Person (String aName) { ... }
public String getName() { ... }
public int compareTo(Person o) { ... }
@Override
public String toString() {
return "My name is " + name; // For the example, you could return any String you want
}
}
方法通常用于提供对象的描述。