使用一种方法在java中打印数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19776132/
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
using a method to print an array in java
提问by user2914418
From my current code how would i print the array{10,20,30,40,50,60,70,88,99,100} using a method display and calling it using System.out.println(myobject.display()) in my main.
从我当前的代码中,我将如何使用方法 display 打印数组{10,20,30,40,50,60,70,88,99,100} 并使用 System.out.println(myobject.display()) 在我的主要。
public TestA(){
index = -1;
iA = new int[]{10,20,30,40,50,60,70,88,99,100};
}
public static String display(){
String str = "";
for(int i = 0; i < 10; i++){
str= str+ " ";
}//for
return str;
}//display
My current method display does not display anything.
我当前的方法显示没有显示任何内容。
回答by Martijn Courteaux
You need to call the method and print the result. Also use the array iA
in your method.
您需要调用该方法并打印结果。还可以iA
在您的方法中使用该数组。
System.out.println(display());
回答by Sudhakar Tillapudi
public TestA()
{
index = -1;
iA = new int[]{10,20,30,40,50,60,70,88,99,100};
System.out.println(display(iA));
}
public static String display(int[] myData)
{
String str = "";
for(int i = 0; i < myData.length; i++){
str += myData[i]+ " ";
}
return str;
}
回答by Walls
Your for loop is just adding an empty string to an empty string 10 times. You are never adding in the text from your array based on the index i
. During your loop, you should be adding the space as well as the value at the current array position.
您的 for 循环只是将空字符串添加到空字符串 10 次。您永远不会根据索引从数组中添加文本i
。在循环期间,您应该添加空间以及当前数组位置的值。
回答by Dale Myers
Your method display()
is indeed doing something. It is returning 10 spaces, which are being printed out in your main method. You need to actually use the array at some point. Try something like:
你的方法display()
确实在做一些事情。它返回 10 个空格,这些空格在您的 main 方法中打印出来。您需要在某个时候实际使用该数组。尝试类似:
public TestA(){
index = -1;
iA = new int[]{10,20,30,40,50,60,70,88,99,100};
}
public static String display(int[] iA){
String str = "";
for(int i = 0; i < 10; i++){
str= str + Integer.toString(iA[i]) + " ";
}//for
return str;
}//display