samedi 9 juillet 2016

How to create new object in a for loop?

I want to create some objects in a program using for loop. The parameters of the objects are accepted from key board. My question is how to create different objects in a for loop. Here is what I have.

import java.io.*;
import java.util.*;
public class TimeToGraduate {

public static void main(String[] args){

    class Course{
        Course (String name, String sem, int numOfPre){
            this.name = name;
            this.sem = sem;
            this.numOfPre = numOfPre;
        }
        String name;
        String sem;
        int numOfPre;
    }

    Scanner scanner = new Scanner(System.in);
    System.out.print("Input two integers here: ");
    String totalCourse = scanner.nextLine();
    String[] numOfCourse = totalCourse.split(" ");//[0] num of total course  [1] max num per semester

    for(int i = 0;i < Integer.parseInt(numOfCourse[0]); i++){
        System.out.print("Please input course info here: ");
        String courseInfo = scanner.nextLine();
        String[] infoOfCourse = courseInfo.split(" ");

        String courseName = infoOfCourse[0];
        String courseSem = infoOfCourse[1];
        int courseNumOfPre = Integer.parseInt(infoOfCourse[2]);

        Course course = new Course(courseName,courseSem,courseNumOfPre);

 //How to create different objects?

    }

    scanner.close();
}
}

Aucun commentaire:

Enregistrer un commentaire