java打印并返回的数组

时间:2016-07-14 05:59:11

标签: java arrays

我是java的新手,正在做一些练习。我一直在研究数组,并且能够打印出我的第一个数组。但是第二个没有打印任何东西,只是想知道我哪里出错了,非常感谢你。

package Justice;

import java.util.Arrays;

class ArrayDemo {
    public static void main(String[] args) {
    int[] anArray;

    anArray = new int[10];

    anArray[0] = 100;
    anArray[1] = 200;
    anArray[2] = 300;
    anArray[3] = 400;
    anArray[4] = 500;
    anArray[5] = 600;
    anArray[6] = 700;
    anArray[7] = 800;
    anArray[8] = 900;
    anArray[9] = 1000;
    System.out.println (Arrays.toString(anArray));

}  


public static String[] hello(String[] args) {
    String[] myArray;


    myArray = new String[5];
    myArray[0] = "hello";
    myArray[2] = "world";

    System.out.println(Arrays.toString(myArray));
    return (myArray);

}

6 个答案:

答案 0 :(得分:1)

public static void main(String[] args)
如果从shell运行Java类,则会调用

如果你想打电话

hello(String[] args)

你必须在main方法中明确地调用它。您可以在第一个打印语句下面添加以下行:

hello(null);

答案 1 :(得分:0)

请尝试deepToString(Object[])方法,而不是toString(args)

您可以尝试使用方法deepToString(Object[])来显示该数组的所有内容。

String [] arr = new String[3];
arr[0]="asdf";
arr[1]="asdf";
System.out.println(Arrays.deepToString(arr));

它将打印输出,如

[asdf, asdf, null]

另一种方法是...... 你也可以在forloop中将长度作为一个标准来迭代这个数组。

for(int i=0 i<anArray.length;i++)
System.out.println(anArray[i]);

感谢YOu

答案 2 :(得分:0)

在System.out.println(Arrays.toString(anArray))之后粘贴此System.out.println(hello(args));;

会为您提供输出:[hello, null, world, null, null]

答案 3 :(得分:0)

只需将其添加到您的代码中

即可
package Justice;

import java.util.Arrays;

class ArrayDemo {
    public static void main(String[] args) {
    int[] anArray;

    anArray = new int[10];

    anArray[0] = 100;
    anArray[1] = 200;
    anArray[2] = 300;
    anArray[3] = 400;
    anArray[4] = 500;
    anArray[5] = 600;
    anArray[6] = 700;
    anArray[7] = 800;
    anArray[8] = 900;
    anArray[9] = 1000;
    System.out.println (Arrays.toString(anArray));

    // This is the method call
    hello(null);             // You don't need the 'String[] args' in your method because you've not used the arguments


}  


public static String[] hello(String[] args) {
    String[] myArray;


    myArray = new String[5];
    myArray[0] = "hello";
    myArray[2] = "world";

    System.out.println(Arrays.toString(myArray));
    return (myArray);

}

答案 4 :(得分:0)

只需将您的main()更改为:

class ArrayDemo { 
public static void main(String[] args) {

int[] anArray;

anArray = new int[10];

anArray[0] = 100;
anArray[1] = 200;
anArray[2] = 300;
anArray[3] = 400;
anArray[4] = 500;
anArray[5] = 600;
anArray[6] = 700;
anArray[7] = 800;
anArray[8] = 900;
anArray[9] = 1000;
System.out.println (Arrays.toString(anArray));

ArrayDemo obj = new ArrayDemo();
obj.hello();
}

然后像这样制作hello()方法:

public void hello() {
String[] myArray;


myArray = new String[5];
myArray[0] = "hello";
myArray[2] = "world";

System.out.println(Arrays.toString(myArray));
}

答案 5 :(得分:0)

public static String [] hello(String [] args)未被调用。它应该从public static void main()中调用。