0

So I was attempting to help someone over at CodeReview, and my suggested code didn't compile! Oh no! Now, this code is substantially different from their original code, so I feel no qualms posting my botched answer with you guys. The compiler (STS) is complaining about line 14 in my code students[i] = new Student();. Here's my error:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: No enclosing instance of type studentexams is accessible. Must qualify the allocation with an enclosing instance of type studentexams (e.g. x.new A() where x is an instance of studentexams). at cr_studentscoreaverager.studentexams.main(studentexams.java:16)

I am not asking for a critique of the code or style, just my implementation of the Student class resulting in my compile error.

Here is my code in its entirety.

import java.util.Scanner;

public class studentexams
{

    public static void main(String[] args) 
    {
        Scanner input = new Scanner(System.in);

        Student[] students = new Student[20];

        for (int i = 0; i < 20; i++)
        {
            students[i] = new Student();
            students[i].setStudentName("Student " + (i+1));
            System.out.print("Enter the first score: ");
            students[i].setScores(0,  input.nextInt());
            System.out.print("Enter the Second Score: ");
            students[i].setScores(1,  input.nextInt());
            System.out.print("Enter the third Score: ");
            students[i].setScores(2,  input.nextInt());
            System.out.println("The Average Score is " + students[i].getAverage());
        }

        System.out.println("Student" + "\t" + "Average");

        for(int i = 0; i < 20; i++)
        {
            System.out.println(students[i].toString());
        }
     }

    public class Student
    {
        private String studentName;
        private int[] scores = new int[3];
        private double average;

        public Student()
        {
        }

        private String getStudentName()
        {
            return this.studentName;
        }

        public void setStudentName(String studName)
        {
            this.studentName = studName;
        }

        public void setScores(int index, int score)
        {
            this.scores[index]=score;
        }

        public double getAverage()
        {
            average = (double) (scores[0]+scores[1]+scores[2])/3;
            return average;
        }

        public String toString()
        {
            return this.getStudentName() + "\t\t" + this.getAverage();
        }
    }
}
  • 1
    You created the array `Student[] students = new Students[20]`, but you have not created an object to insert into that array. In the `for` loop, add `students[i] = new Student()`. – KevinO Apr 13 '16 at 03:17
  • @KevinO This is my answer. Thank you. I have other issues now. I have updated and edited my question. – Wayman Bell III Apr 13 '16 at 03:40

0 Answers0