Home>

I want to create a method of Student class that gets and returns the name corresponding to the number specified by the argument (nStudent) from the array aryStudent that stores the names.

Currently code like this:

import java.util.Scanner;
public class Student {
    public String SerchStudent(int nStudentNo) {
        nStudentNo = nNum;
        return nStudentNo;
    }

    public static void main(String[] args) {
        String[] aryStudent = {"Ichiro Suzuki", "Taro Sato", "Saburo Tanaka"};
        System.out.println("Please enter the student number whose name I want to confirm:");
        Scanner scImput = new Scanner(System.in);
        int nNum = scImput.nextInt();

    }
}

But in the Serch Student method I get an error that nNum cannot be resolved in a variable.

Please give us your advice.

  • Answer # 1

    I tried to write it while respecting the original code as much as possible.
    An error will occur if the input receives anything other than 0, 1, 2 but for the time being, emphasize simplicity.

    import java.util.Scanner;
    public class Student {
        static String[] aryStudent = {"Ichiro Suzuki", "Taro Sato", "Saburo Tanaka"};
        public static String SerchStudent(int nStudentNo) {
            // nStudentNo = nNum;
            return aryStudent[nStudentNo];
        }
        public static void main(String[] args) {
            System.out.println("Please enter the student number whose name you want to confirm:");
            Scanner scImput = new Scanner(System.in);
            int nNum = scImput.nextInt();
            String studentName = SerchStudent(nNum);
            System.out.println(studentName);
        }
    }