[英]Passing an array back to a main method
這是主要方法:
public static void main(String[] args) throws IOException{
int [] array = new int [1000];
int[] getArray=FileArrayProvider(array);
for (int y = 0; y < getArray.length; ++y)
{
System.out.print(array[y] + " ");
}
我想將“數組”傳遞到下面的方法“ FileArrayProvider”中:
public static int[] FileArrayProvider(int[] array1) throws IOException{
File file = new File("RandomNumbers.txt");
FileReader inputFile = new FileReader(file);
BufferedReader in = new BufferedReader(inputFile);
{String s =in.readLine();
System.out.println("Array before sorting: ");
while(s!=null)
{int k = 0;
array1[k] = Integer.parseInt(s);
System.out.print(array1[k]+" ");
s = in.readLine();
}
in.close();
}
return array1;
}
問題在於該數組未傳遞回main方法。 它可以在'FileArrayprovider'方法中正確打印,但是僅將數組的最后一個值傳遞回main方法,並且用除此以外的所有零填充數組。 任何提示或建議將不勝感激以解決此問題!
因為在for循環中,您要在main()中打印數組
System.out.print(array[y] + " ");
您正在打印array[y]
而不是打印新值getArray
我注意到的一件事是,在您的FileArrayProvider()
方法中,從本質FileArrayProvider()
僅更改array1
的第一個值就不會增加int k
。 將其更改為此,看看是否可行。
String s =in.readLine();
System.out.println("Array before sorting: ");
int k = 0;
while(s!=null)
{
array1[k] = Integer.parseInt(s);
System.out.print(array1[k]+" ");
s = in.readLine();
k++;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.