java - 如何访问从方法传递的数组以便在主方法中重新排列它
问题描述
public class ICT_Questions_34 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the Index of Numbers");
int n = input.nextInt();
RandomNumber(n);// It returns n number of 2 digit numbers at here.
System.out.println(myList.length);
System.out.println(myList[2]);
// there seems to be a problem here as the method I called prior this statements is as if it isn't working. What's the problem
}
public static int[] RandomNumber(int n) {
if (n < 0) {
System.out.println("PLEASE Enter Positive Number!");
}
int[] myList = new int[n];
for (int i = 0; i < n; i++) {
int Values = (int) ((90 * Math.random()) + 10);
System.out.print(Values + "\t");
for (int j = i; j < n; j++) {
myList[j] = Values;
}
}
return myList;
}
}
解决方案
的范围是int[] myList
该方法的本地范围,public static int[] RandomNumber(int n)
因此无法在该方法之外访问它。
但是您正在返回数组,因此您可以像代码一样访问该main
方法。int[] myList = RandomNumber(n);
public class ICT_Questions_34 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the Index of Numbers");
int n = input.nextInt();
int[] myList = RandomNumber(n);// It returns n number of 2 digit numbers at here.
System.out.println(myList.length);
System.out.println(myList[2]);
// there seems to be a problem here as the method I called prior this statements is as if it isn't working. What's the problem
}
public static int[] RandomNumber(int n) {
if (n < 0) {
System.out.println("PLEASE Enter Positive Number!");
}
int[] myList = new int[n];
for (int i = 0; i < n; i++) {
int Values = (int) ((90 * Math.random()) + 10);
System.out.print(Values + "\t");
for (int j = i; j < n; j++) {
myList[j] = Values;
}
}
return myList;
}
}
推荐阅读
- arrays - 无法找到代码的失败测试用例
- ios - 是否可以跟踪用户从 App Store 的下载?
- ethereum - 如何将空字节传递给 Remix 中的solidity 函数?
- regex - 请帮助使用 .htaccess 更改网站网址
- openhtmltopdf - OpenHTMLtoPDF 将字符显示为 #
- neoscms - Neos 编辑器 - 页面重新加载后删除的节点重新出现
- python - 在 Google Colab 中确定路径
- python - Python 中我的 try-except 中的 while-loop
- flutter - 可注入的 get_it Flutter 的性能
- python - 选择列表中每个列表的第一个元素