从一种方法打印数组到另一种方法
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了从一种方法打印数组到另一种方法相关的知识,希望对你有一定的参考价值。
我创建了一个字符串数组和一个2d双数组,并在initializeData()方法中填充了两个值。现在我正在尝试在displayData()方法中显示数组。
我设法使用嵌套的for循环在initializeData()中显示数据。
for(int i = 0; i<students.length; i++) {
System.out.print(students[i] + " ");
for(int j = 0; j<grades.length; j++) {
System.out.print(grades[i][j] + " ");
}
System.out.println("");
}
如何在displayData()中使用上面这个相同的循环并在方法initializeData()中显示数组?
public class Assignment2 {
public static void main(String[] args) {
initializeData();
displayData();
}
/**
* Method that initializes 5 students and grades for 5 courses and populates data.
*/
public static void initializeData() {
//create arry with student names
String[] students = {"James", "Luke", "Alex", "Jenny"};
//create 2d array and populate it
double grades[][] = {{98, 72, 85, 77, 90},{25,49,26,77,60},{13,8,46,52,28},{77,81,85,69,88}};
}
/**
* Method that takes the data from initializeData() and displays it to the screen.
*/
public static void displayData() {
}
答案
您的数组本地作用于initialize方法,并且您有两个对象,因此您无法将它们返回到main方法,因此您唯一的选择(除了从初始化方法调用display方法)是使用类变量将变量范围移动到整个类
import java.util.Arrays;
public class Assignment2 {
static String[] students;
static double[][] grades;
public static void main(String[] args) {
initializeData();
displayData();
}
/**
* Method that initializes 5 students and grades for 5 courses and populates data.
*/
public static void initializeData() {
//create arry with student names
students = new String[] {"James", "Luke", "Alex", "Jenny"};
//create 2d array and populate it
grades = new double[][] {{98, 72, 85, 77, 90},{25,49,26,77,60},{13,8,46,52,28},{77,81,85,69,88}};
}
/**
* Method that takes the data from initializeData() and displays it to the screen.
*/
public static void displayData() {
System.out.println(Arrays.toString(students));
}
}
另一个选项包括这样的方法,但您需要了解自定义类
Student[] initializeData() {}
void displayData(Student[] students) {}
static void main (String[] args) {
Student[] students = initializeData();
displayData(students);
}
以上是关于从一种方法打印数组到另一种方法的主要内容,如果未能解决你的问题,请参考以下文章