java - 如何在 JAVA 中从一种方法访问对象数组到另一种方法?
问题描述
我创建了一个对象数组,该数组是从此处名为 dataInput() 的方法创建的。我想在 main 方法中调用 people 数组。提前致谢。
public static void dataInput() {
Scanner input = new Scanner(System.in);
int noOfPersons = 3;
String name = "";
int no = 0;
String city = "";
inputTry[] persons = new inputTry[3];
persons[0] = new inputTry(name, no, city);
persons[1] = new inputTry(name, no, city);
persons[2] = new inputTry(name, no, city);
for (int i = 0; i < noOfPersons; i++) {
System.out.print("Enter person name: ");
name = input.nextLine();
System.out.print("Enter person number: ");
no = input.nextInt();
input.nextLine();
System.out.print("Enter where the person lives: ");
city = input.nextLine();
persons[i].name = name;
persons[i].no = no;
persons[i].city = city;
}
}
解决方案
如果
dataInput()
在main
的同一类中, 您可以在“类的开头”声明这个数组全局。如果
dataInput()
不在main
类中, 您可以创建一个名为 example 的公共方法,getPersonsArray()
并从dataInput()
. 现在您可以从此类中获取对象并调用方法getPersonsArray()
。
public static void dataInput() {
// your code
inputTry[] persons = new inputTry[3];
getPersonsArray(name, no, city);
// your code
}
public static inputTry[] getPersonsArray(String name,int no,String city) {
persons[0] = new inputTry(name, no, city);
persons[1] = new inputTry(name, no, city);
persons[2] = new inputTry(name, no, city);
return persons;
}
推荐阅读
- python - 创建一个网页,它要求一些输入并将其写入文件
- javascript - 为什么这个使用 react-hook-form 的表单不会重置回 defaultValues?
- r - lubridate:floor_date 设置参考开始时间戳
- java - JNI调用Android对话框,等待用户选择
- google-maps-api-3 - 华为设备没有在我的应用程序中加载谷歌地图
- ruby - 根据创建的方法更改地点索引(RUBY 挑战)
- php - PHP:从字符串数组中删除“\u00a0”
- c# - 并行:打印 CPU 核心数
- visual-studio-code - 如何更改代码运行器中使用的外壳?
- c# - 在实体框架中,我可以创建一个计算列来计算每一行的所有值吗?