从java中的对象中检索值... [英] Retrieve values from object in java...
问题描述
我有一个收集学生反馈的计划。我已将其存储在ArrayList中。我有一个名为display()的方法,它将显示反馈详细信息。但是当我调用方法时,它显示其他值(引用地址或地址)而不是对象的实际细节。**我只调用了数组的第0个元素进行测试。**下面是代码...
--------------------------------------------- --------------
I have a program which gathers feedback from students. I have stored it in an ArrayList. I have a method named display() which will display the feedback details. But when I call the method it shows other values(reference address or address) not the actual details of the object.** I have only called the 0th element of array for testing.** Below is the code...
-----------------------------------------------------------
import java.util.*;
import java.io.*;
class FeedBack
{
int enroll;
String name;
String feedback;
String subject;
public void getFeedback()
{
Scanner s=new Scanner(System.in);
System.out.println("Enter Enrollment No:");
enroll=s.nextInt();
System.out.println("Enter Name:");
name=s.next();
System.out.println("Enter feedback:");
feedback=s.next();
System.out.println("Enter Subject:");
subject=s.next();
}
public void display(ArrayList al)
{
System.out.println("Given FeedBack....!");
System.out.println(al.get(0));
}
}
class StudFeedback
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
FeedBack fb,fb1;
fb1=new FeedBack();
ArrayList<feedback> al=new ArrayList<feedback>();
int c;
do
{
System.out.println("Do you want to give Feedback 1 or 0 ?");
c=Integer.parseInt(br.readLine());
if(c==1)
{
fb=new FeedBack();
fb.getFeedback();
al.add(fb);
}
else
{
break;
}
}while(c!=0);
fb1.display(al);
}
}
--------------------- ------------------------
---------------------------------------------
推荐答案
您的FeedBack
class不包含toString
方法的覆盖。因此,当您在ArrayList< feedback>
列表的元素上调用println
时,这是FeedBack
对象,它不知道如何打印它,所以它只打印内存地址。
YourFeedBack
class does not include an override of thetoString
method. So when you callprintln
on an element of theArrayList<feedback>
list, which is aFeedBack
object, it has no idea how to print it, so it just prints the memory address.
这是因为默认的toString实现提供了这样的信息(即对象类型和地址)。但是,您可以覆盖它(在FeedBack
类中)提供您自己的toString
方法的实现。例如
That happens because the default toString implementation provides such a info (that is object type and address). However, you may override it providing (inFeedBack
class) your own implementation of thetoString
method. For example
public String toString()
{
String result = String.format("Enrollment No: %d\nName: %s\nFeedback: %s\nSubject: %s\n", enroll, name, feedback, subject);
return result;
}
这篇关于从java中的对象中检索值...的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!