如何将void方法结果存储到int数组方法中

时间:2014-05-29 11:02:25

标签: java arrays

我试图将public static void readGrades()的结果存储到方法数组int []成绩中。但我没有这样做。不幸的是,我尝试了ArrayList和其他东西。

public static int[]grades;
public static void main(String[] args) {
        readGrades();
}
public static void readGrades(){
    Scanner in=new Scanner(System.in);
    System.out.print("How many students there are : ");
    int numberOfStudents=in.nextInt();
    for(int i=1;i<=numberOfStudents;i++){
    System.out.print("Enter the grade of the students : ");
    int grades1=in.nextInt();
    grades1++;
}

2 个答案:

答案 0 :(得分:1)

试试这个:

public static int[] grades;
public static void main(String[] args) {
        readGrades();
}
public static void readGrades(){
    Scanner in=new Scanner(System.in);
    System.out.print("How many students there are : ");
    int numberOfStudents=in.nextInt();
    grades=new int[numberOfStudents];
    for(int i=0;i<numberOfStudents;i++){
        System.out.print("Enter the grade of the students : ");
        int grade=in.nextInt();
        grades[i]=grade;
     }
}

你必须知道这会将数据存储在grades数组中,你可以使用它调用方法readGrades(),尝试编写在readGrades()之后打印成绩的代码。

答案 1 :(得分:1)

您无需声明grades[] static,也可以使用locally declared int[]进行声明,如下所示:

public static void main(String[] args) {
        Scanner in=new Scanner(System.in);
        System.out.print("How many students there are : ");
        int numberOfStudents=in.nextInt();
        int[] grades = new int[numberOfStudents];
        readGrades(grades, in);
        // here you can write code to play with grades array
}
public static void readGrades(int[] grades, Scanner in){
    for(int i=0;i<numberOfStudents;i++){
         System.out.print("Enter the grade of the students : ");
         grades[i]=in.nextInt();
    }
}

希望这有帮助。