需要为用户生成每个学生的卷号吗?

时间:2018-06-06 04:52:18

标签: java arrays function class object

我需要从每个学生那里得到独特的卷号。

package test;

import java.util.Scanner;

public class Studentform {

    public static void main(String[] args) {

        int length = 3;

        Studb[] studs = new Studb[length];

        for (int i = 0; i < length; i++) {
            for (Studb s : studs) {
                readStudent(i);

            }
        }

    }

    static void readStudent(int i) {
        int rollno = 1001;
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter your name:");
        String name = sc.next();
        System.out.println("Enter your age:");
        int age = sc.nextInt();
        Studb stud = new Studb(name, age, rollno++);
        System.out.println(stud);

    }
}

2 个答案:

答案 0 :(得分:0)

只要传递它,它也最终是独一无二的。如下:

static void readStudent(int i) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter your name:");
        String name = sc.next();
        System.out.println("Enter your age:");
        int age = sc.nextInt();
        Studb stud = new Studb(name, age, i);
        System.out.println(stud);

    }

或者您可以在rollno中添加i值,例如:

static void readStudent(int i) {
        int rollno = 1000+i;
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter your name:");
        String name = sc.next();
        System.out.println("Enter your age:");
        int age = sc.nextInt();
        Studb stud = new Studb(name, age, rollno);
        System.out.println(stud);

    }

答案 1 :(得分:0)

    package test;

    import java.util.Scanner;

    public class Studentform {

        public static void main(String[] args) {

            int length = 3;

            Studb[] studs = new Studb[length];

            for (int i = 0; i < length; i++) {

                studs[i] = readStudent(i);

            }

            for (int i = 0; i < length; i++) {

                System.out.println(studs[i]);

            }

        }

        static Studb readStudent(int i) {
            int rollno = 1000+i++;
            Scanner sc = new Scanner(System.in);
            System.out.println("Enter your name:");
            String name = sc.next();
            System.out.println("Enter your age:");
            int age = sc.nextInt();
            return new Studb(name, age, rollno);
            //System.out.println(stud);
            //return stud;
        }
    }