[英]printing out attributes of multiple objects in java
I have created a person class, with attributes age and name. 我创建了一个具有年龄和姓名属性的人员类。 I have created 5 instances of the class in an object array as well, and would like to print the attributes out with a for loop. 我也在对象数组中创建了该类的5个实例,并希望使用for循环将属性打印出来。 It is my understanding that toString
is explicitly called when you try to print out an object, so I override toString
so that it prints out both attributes of the object when it is called. 据我了解,当您尝试打印一个对象时, toString
被显式调用,因此我覆盖了toString
以便在调用该对象时它打印出该对象的两个属性。
Here is my code: 这是我的代码:
class Person
{
int age;
String name;
public Person(String name, int age)
{
this.age = age;
this.name = name;
}
public String toString(Person p)
{
return "Name: " + p.name +"Age: "+ p.age;
}
}
public class P1Q5Bubble {
public static void main(String[] args) {
Person [] pp = new Person [5];
pp[0] = new Person("Andy" , 18);
pp[1] = new Person("Lisa" , 20);
pp[2] = new Person("Bob" , 10);
pp[3] = new Person("Eva" , 18);
pp[4] = new Person("Tim" , 13);
for(int i = 0; i> pp.length ; i++)
System.out.println(pp[i]);
}
You need to change two things 你需要改变两件事
1) in for i > pp.length
to i < pp.length
1)在i > pp.length
到i < pp.length
2) toString()
method used in System.out.print
or System.out.println
doesn't have arguments so change it to something like 2) System.out.print
或System.out.println
中使用的toString()
方法没有参数,因此请将其更改为类似
public String toString() {
return "Name: " + name + "Age: " + age;
}
Your for
loop terminating condition is incorrect, you need i < pp.length
. 您的for
循环终止条件不正确,您需要i < pp.length
。
Using i > pp.length
your loop will execute no statements. 使用i > pp.length
您的循环将不执行任何语句。 The loop will only execute so long as the terminating condition is true
. 仅当终止条件为true
,循环才会执行。
Furthermore you're not overriding toString
correctly: your toString
method shouldn't take any arguments: your instance variables name
and age
will be available to the function. 此外,您没有正确地重写toString
:您的toString
方法不应使用任何参数:您的实例变量name
和age
将对函数可用。
The toString() function which you need to override in Person class should not contain any argument (since the Object class in which it is defined does not contain an argument). 在Person类中需要重写的toString()函数不应包含任何参数(因为在其中定义了该对象的Object类不包含参数)。 The corrected code for that function will be 该函数的更正代码将是
@Override public String toString()
{
return return "Name: " + name +"Age: "+ age;
}
You should override default toString() (with no arguments) instead you have added a new method. 您应该覆盖默认的toString()(不带参数),而是添加了一个新方法。 So remove that argument and use 'this' in place of person argument 因此,请删除该参数,并使用“ this”代替个人参数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.