Search code examples
javaobject-oriented-analysis

can't set a value in another class


This is a method from a class, courses is an array from another class, I set the value of cn in main, but it skips all the codes after it. Why is that?

public class GradeBook {
    Scanner r=new Scanner(System.in);
    private int cn;
    private Course courses[]=new Course[cn];
    void entercourse(){
         for(int i = 0;i<courses.length;i++){
             System.out.println("c name");
             courses[i].setName(r.nextLine());
             System.out.println("mark");
             courses[i].setMark(r.nextInt());
             courses[i].setpass();
         }
    }

Solution

  • When you declare an array outside of a method, you need to specify an array size value. In your program, you used the integer cn. However, you did not specify what "cn" actually represents, so by default, it became 0. That is why your array is empty and your program seemingly skips the code.