java java打印带有Arrays.toString()错误的数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12917166/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 10:46:47  来源:igfitidea点击:

java printing an array with Arrays.toString() error

javaarraystostring

提问by Levon Tamrazov

So I was trying to print an array of ints in my program, and following these instructions What's the simplest way to print a Java array?

所以我试图在我的程序中打印一个整数数组,并按照这些说明打印 Java 数组的最简单方法是什么?

wrote the following code:

写了以下代码:

    int[] totals = //method that returns int array
    System.out.println(Arrays.toString(totals));

But it wont compile saying that

但它不会编译说

"method toString in class Object cannot be applied to given types. required: no arguments found: int[] reason: actual and formal argument list differ in length"

“类 Object 中的 toString 方法不能应用于给定类型。必需:找不到参数:int [] 原因:实际和形式参数列表的长度不同”

Why does it do that? Do I not pass my array as an argument to toString? If not, how do I use toString?

为什么这样做?我不将我的数组作为参数传递给 toString 吗?如果没有,我该如何使用 toString?

Thank you!

谢谢!

回答by Bhesh Gurung

method toString in class Object cannot be applied to given types. required: no arguments found: int[] reason: actual and formal argument list differ in length

类 Object 中的方法 toString 不能应用于给定类型。要求:未找到任何参数:int[] 原因:实际和形式参数列表的长度不同

May be you have a variable named Arrays, that's why the compiler is complaining thinking that you are trying to invoke the Object.toString(), which doesn't take any argument.

可能您有一个名为 的变量Arrays,这就是为什么编译器抱怨您正在尝试调用Object.toString()不带任何参数的 。

Try

尝试

 System.out.println(java.util.Arrays.toString(totals)); 

回答by Omaha

The fact that it says "method toString in class Object cannot be applied to given types." makes me think you might not be importing the java.util.Arraysclass properly, or you have some other object called Arrays.

事实上,它说“类 Object 中的方法 toString 不能应用于给定的类型。” 让我觉得您可能没有正确导入java.util.Arrays类,或者您有其他一些名为Arrays.

回答by Mik378

This works for me:

这对我有用:

int[] totals = {1,2};
System.out.println(Arrays.toString(totals));

printing:

印刷:

[1, 2]

Are you sure you use at least JDK 5?

您确定至少使用JDK 5吗?

Indeed, Arrays.toString(int[] a)only exists since JDK 5.

事实上,Arrays.toString(int[] a)只存在于 JDK 5 之后。

回答by Lo Juego

Your method doesn't seem to init your array, try this:

你的方法似乎没有初始化你的数组,试试这个:

int[] totals = new int[10]; //method that returns int array
System.out.println(Arrays.toString(totals));

回答by Sashi Kant

Why dont you try ::

你为什么不试试 ::

int[] totals = //method that returns int array
    System.out.println(totals.toString());