从java中的对象中检索值... [英] Retrieve values from object in java...

查看:58
本文介绍了从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 对象,它不知道如何打印它,所以它只打印内存地址。
Your FeedBack class does not include an override of the toString method. So when you call println on an element of the ArrayList<feedback> list, which is a FeedBack 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 (in FeedBack class) your own implementation of the toString 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆