为什么我的阵列不能正确打印出来? [英] Why won't my array print out correctly?

查看:122
本文介绍了为什么我的阵列不能正确打印出来?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用下面的代码编写一个简单的程序来创建一个单维数组,然后您可以使用索引号调用一个值。我正在使用 java eclipse 作为我的编译器。每当我尝试调试或运行程序时,完整数组就会打印出来: [I @ 1fa8d3b

I am trying to write a simple program using the code below to make a single dimensional array that you can then call a value from using the index numbers. I am using java and eclipse as my compiler. Whenever I try to debug or run the program, the full array prints out as this: [I@1fa8d3b.

class Array    
{
public static void main(String[] args)
{
    int[] MyArray = new int[] {15, 45, 34, 78, 65, 47, 90, 32, 54, 10};
    System.out.println("The full array is:");
    System.out.println(MyArray);
    System.out.println("The 4th entry in the data is: " + MyArray[3]);
}
}

正确的数据条目在被调用时打印出来。我试图在网上寻找我应该做什么的答案,但我找不到任何有效的东西。我刚刚开始学习Java所以可能有一个非常简单的答案,我只是忽略了。如果有人有任何想法,我将非常感激。

The correct data entry prints out when it is called though. I have tried to look for answers online as to what I should do, but I could not find anything that actually works. I am just starting to learn Java so there could be a very simple answer to this that I am just overlooking. If anyone has any ideas, I would be greatly appreciative.

推荐答案

Java是一种面向对象的语言。当您在Java中调用 System.out.print(MyArray); 时,实际上是在内存中打印堆上对象的地址来自它的父类对象的toString代码,下面显示的代码由EngFouad的评论提供,对不起发言。您看到打印出的奇怪字符串是当您询问与变量 MyArray 相关联的内容时计算机用于查找数据的引用。

Java is an object oriented language. When you are calling System.out.print(MyArray); in Java you are actually printing the address of the object on the heap in memory the toString code from it's parent class Object, the code is shown below contributed by the comment from EngFouad, sorry for misspeaking. The weird String you see printed out is the reference the computer uses to find your data when you ask for something associated with the variable MyArray.

如其他答案所述,要打印出对象的数据,您可以使用中内置的数组类.toString ()方法。这将打印来自对象的数据,而不仅仅是对象引用。

As stated by the other answers, to print out the data of your object you can use the Array class's built in .toString() method. This will print the data from the object instead of just the object reference.

System.out.println(Arrays.toString(MyArray);

更正
实际上是toString()类Object:getClass()。getName()+@+ Integer.toHexString(hashCode())。 - Eng.Fouad

Correction Actually it is toString() of the class Object: getClass().getName() + "@" + Integer.toHexString(hashCode()). – Eng.Fouad

上述错误已得到纠正,谢谢评论,讨厌给出错误的信息。我自己误解了。以下是查看代码的API参考:

Mistake above was corrected thanks for the comments, hate to give the wrong information. I misunderstood it myself. Here is the API reference to see the code:

http://docs.oracle.com/javase/1.5.0/docs /api/java/lang/Object.html#toString()

这篇关于为什么我的阵列不能正确打印出来?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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