简体   繁体   中英

How to use array from one method in another?

I find problem to use array form one method in another method.

In first method I take input from user and saved data to two arrays.

In second method I have to shows these information from array.

import java.util.Scanner;

public class MarkCalculator {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        computeMark();
        computeResult();
    }

    public static void computeMark ()
    {

        Scanner exam = new Scanner (System.in);
        Scanner coursework = new Scanner (System.in);

        int num = 12;
        int[] exam_grade = new int[num];
        int[] coursework_grade = new int[num];

        for (int i=0+1; i<3; i++){

           System.out.printf(i+". Modelue"+" Enter grade of exam:");
           exam_grade[i]=exam.nextInt();

           System.out.printf(i+". Modelue"+" Enter grade of coursework:");
           coursework_grade[i]=coursework.nextInt();   
        }

        System.out.println();   
        System.out.println();
        System.out.println("Your grades are: ");


    }


    public static void computeResult (int[] coursework_grade, int[] exam_grade)
    {

        for (int i = 0+1; i<3; i++) {

            System.out.println(i+". Module: "+ "Exam: "+exam_grade[i]+" Coursework: "+coursework_grade[i]);

        }

    }



}

The problem is, I have no idea how to pass information from array to the second method. I couldn't find any solution. Can someone help me pls?

Thanks.

this is all it takes.

computeResult(coursework_grade,exam_grade);

you can pass an array or any object to a method as you would do with a primitive type. But remember when passing an object if the object's state is changed in the called method it gets reflected in the object itself and all references of the object would contain the affected object.

add the call to the method after:

System.out.println("Your grades are: ");
computeResult(coursework_grade,exam_grade);

make the arrays, global. out them outside the public static void main(String[] args) and it will be global.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM