0

I am a student and looking for help with an assignment. Here is the task: Create a CollegeCourse class. The class contains fields for the course ID (for example, “CIS 210”), credit hours (for example, 3), and a letter grade (for example, ‘A’).

Include get() and set()methods for each field. Create a Student class containing an ID number and an array of five CollegeCourse objects. Create a get() and set() method for the Student ID number. Also create a get() method that returns one of the Student’s CollegeCourses; the method takes an integer argument and returns the CollegeCourse in that position (0 through 4). Next, create a set() method that sets the value of one of the Student’s CollegeCourses; the method takes two arguments—a CollegeCourse and an integer representing the CollegeCourse’s position (0 through 4).

I am getting runtime errors on the second for loop where I am trying to get the data into the course array. It is asking for both the CourseID and Hours in the same line and regardless of what I respond with it I am getting an error, it almost seems like it is trying to get all the arrays variables at the same time. Here is my code which includes three classes. Any help to send me in the right direction is appreciated as I have spent a ton of time already researching to resolve.

public class CollegeCourse {

private String courseId;
private int creditHours;
private char grade;
public CollegeCourse(String id, int hours, char grade)
{
    courseId=id;
    creditHours = hours;
    this.grade = grade;
}

public void setCourseId(String id)
{
    courseId = id;//Assign course id to local variable
}

public String getCourseId()
{
    return courseId;//Provide access to course id
}

public void setHours(int hours)
{
    creditHours = hours;//Assign course id to local variable
}

public int getHours()
{
    return creditHours;//Provide access to course id
}

public void setGrade(char grade)
{
    this.grade = grade;//Assign course id to local variable
}

public char getGrade()
{
    return grade;//Provide access to course id
}
}

Student Class

public class Student {

final int NUM_COURSES = 5;

private int studentId;
private CollegeCourse courseAdd;//Declares a course object
private CollegeCourse[] courses = new CollegeCourse[NUM_COURSES];

//constructor using user input
public Student(int studentId)
{
    this.studentId=studentId;   
}

public void setStudentId(int id)
{
    studentId = id;//Assign course id to local variable
}

public int getStudentId()
{
    return studentId;//Provide access to course id
}

public void setCourse(int index, CollegeCourse course)
{
    courses[index] = course;
}

public CollegeCourse getCourse(int index)
{
    return courses[index];
    //do I need code to return the courseId hours, grade
}       
}

InputGrades Class

import java.util.Scanner;
public class InputGrades {

public static void main(String[] args) {

    final int NUM_STUDENTS = 2;
    final int NUM_COURSES = 3;  

    Student[] students = new Student[NUM_STUDENTS]; 
    int s;//subscript  to display the students
    int c;//subscript to display courses
    int stId;
    int csIndex;
    String courseId = "";
    int hours = 0;
    //String gradeInput;
    char grade = 'z';
    CollegeCourse course = new CollegeCourse(courseId,hours, grade);//not sure if I am handling this correctly

    Scanner input = new Scanner(System.in);

    for(s = 0; s<NUM_STUDENTS; ++s)
    {
        students[s] = new Student(s);   
        System.out.print("Enter ID for student #" + (s+1) + ":");
        stId = input.nextInt();
        input.nextLine();
        students[s].setStudentId(stId);
        for(c=0; c < NUM_COURSES; ++c)
        {               
            csIndex=c;
            System.out.print("Enter course ID #" + (c+1) + ":");
            courseId = input.nextLine();
            course.setCourseId(courseId);
            System.out.print("Enter hours:");
            hours = input.nextInt();
            input.nextLine();
            course.setHours(hours);
            String enteredGrade = "";
                while(enteredGrade.length()!=1) {
                    System.out.print("Enter grade:");
                    enteredGrade = input.nextLine();
                    if(enteredGrade.length()==1) {
                        grade = enteredGrade.charAt(0);
                    } else {
                        System.out.println("Type only one character!");
                    }
                }
            course.setGrade(grade);
            students[s].setCourse(csIndex, course);         
        }
    }

    for(s = 0; s<NUM_STUDENTS; ++s)
    {
        System.out.print("\nStudent# " +
                students[s].getStudentId());
        System.out.println();
        for(c=0;c<NUM_COURSES;++c)
            System.out.print(students[s].getCourse(c) + " ");   
        System.out.println();
    }   
}

}
cccstudent
  • 15
  • 9
  • what is your error? – xro7 Oct 22 '16 at 18:21
  • what exception is thrown? – Minjun Yu Oct 22 '16 at 18:21
  • Can you post the complete Stactrace of the error and maybe indicate which line it happens in? That would help a lot – Gumbo Oct 22 '16 at 18:21
  • Here is the error: Enter grade:Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0 at java.lang.String.charAt(Unknown Source) at InputGrades.main(InputGrades.java:46) – cccstudent Oct 22 '16 at 18:22
  • I wasn't sure if the error was with my student constructor, the getMethod in the Student class or one of the setMethods for the course array...or something totally different. It almost seem like it wants to pass the college course sub and all three variables of the CollegeCourse array at the same time as the error shows the charAt which has to do with the Grade and that is the third variable of the array. – cccstudent Oct 22 '16 at 18:26
  • 1
    I have tried the code above. And the exception is occured when he tried to get the first car of empty string: `input.nextLine().charAt(0)`. See my solution below. – Dániel Kis Oct 22 '16 at 18:34
  • Here is where is was at when it occurred-It accepted the student ID I put in of 9999 and was on the loop for the course id...notice is shows both enter cours ID and Enter hours on the same line: Enter ID for student #01:9999 Enter course ID#01:Enter hours:555 Enter grade:Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0 at java.lang.String.charAt(Unknown Source) at InputGrades.main(InputGrades.java:46) – cccstudent Oct 22 '16 at 18:35
  • I modified the code above with the feedback received. I still have a few issues. When I run the code, on the second loop and loops after it stops after you enter the course id but it does not do this on the first loop...once you hit the Enter key and will continue. My output is also not working right for the courses. Here is a sample of what it prints for just the course: CollegeCourse@55f96302 CollegeCourse@55f96302 CollegeCourse@55f96302 – cccstudent Oct 22 '16 at 19:25

1 Answers1

0

After input.nextInt() you need to add one more input.nextLine(); and than you can read grade.

            System.out.print("Enter hours:");
            hours = input.nextInt();
            input.nextLine();
            course.setHours(hours);

Why it is needed? See this question: Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods

You should add a very simple length validation when you input the grade:

            String enteredGrade = "";
            while(enteredGrade.length()!=1) {
                System.out.print("Enter grade:");
                enteredGrade = input.nextLine();
                if(enteredGrade.length()==1) {
                    grade = enteredGrade.charAt(0);
                } else {
                    System.out.println("Type only one character!");
                }
            }

so the full main class code:

import java.util.Scanner;

/**
 * Created by dkis on 2016.10.22..
 */
public class App {
    public static void main(String[] args) {

        final int NUM_STUDENTS = 10;
        final int NUM_COURSES = 5;

        Student[] students = new Student[NUM_STUDENTS];
        //String name;
        int s;//subscript  to display the students
        int c;//subscript to display courses
        int stId;
        int csIndex;
        String courseId = "";
        int hours = 0;
        char grade = 'z';
        CollegeCourse course = new CollegeCourse(courseId,hours, grade);//not sure if I am handling this correctly

        Scanner input = new Scanner(System.in);

        for(s = 0; s<NUM_STUDENTS; ++s)
        {
            students[s] = new Student(s);
            System.out.print("Enter ID for student #" + s+1 + ":");
            stId = input.nextInt();
            input.nextLine();
            students[s].setStudentId(stId);
            for(c=0; c < NUM_COURSES; ++c)
            {
                //CollegeCourse course = students[s].getCourse(c);
                csIndex=c;
                System.out.print("Enter course ID#" + c+1 + ":");
                courseId = input.nextLine();
                course.setCourseId(courseId);
                System.out.print("Enter hours:");
                hours = input.nextInt();
                input.nextLine();
                course.setHours(hours);

                String enteredGrade = "";
                while(enteredGrade.length()!=1) {
                    System.out.print("Enter grade:");
                    enteredGrade = input.nextLine();
                    if(enteredGrade.length()==1) {
                        grade = enteredGrade.charAt(0);
                    } else {
                        System.out.println("Type only one character!");
                    }
                }
                course.setGrade(grade);
                students[s].setCourse(csIndex, course);
            }
        }

        for(s = 0; s<NUM_STUDENTS; ++s)
        {
            System.out.print("\nStudent# " +
                    students[s].getStudentId());
            for(c=0;c<NUM_COURSES;++c)
                System.out.print(students[s].getCourse(c) + " ");
            System.out.println();
        }
    }
}
Community
  • 1
  • 1
Dániel Kis
  • 1,445
  • 21
  • 36
  • I modified my code above as suggested and I am getting it to accept the input. On the second loop of adding in the course, after you input the course ID it is stops and doesn't showt the next line until after you hit the Enter key. I also wanted it to count the students as 1, 2...but it is showing 01, 11,etc...for the student and the course # is 01, 11, 21, etc. the output for the Student is okay, but the output for the courses is showing: Student# 1CollegeCourse@55f96302 CollegeCourse@55f96302 – cccstudent Oct 22 '16 at 19:12
  • Oops, I have left `System.out.println();` in the 2nd block, I will correct it – Dániel Kis Oct 22 '16 at 19:38
  • I added modified my code and the input is working perfect, That for your help Daniel. I am now having an issue with my output, the Student part prints perfect but the courses are not printing out. Can you point me in the right direction? – cccstudent Oct 22 '16 at 20:02
  • I modified my code at the top and it works for input and the output for Student work, but the output for the Course array is not working. My guess is it has to do with the getCourse method. I am not sure how to use the getCourse method to pull the variables of the course array. – cccstudent Oct 22 '16 at 20:10
  • To output: you can add a toString() method to Student and CollegeCourse class:`@Override public String toString() { return "Student{" + "studentId=" + studentId + ", courseAdd=" + courseAdd + ", courses=" + Arrays.toString(courses) + '}'; }` and to CollegeCourse: `@Override public String toString() { return "CollegeCourse{" + "courseId='" + courseId + '\'' + ", creditHours=" + creditHours + ", grade=" + grade + '}'; }` – Dániel Kis Oct 22 '16 at 20:14
  • stack overflow comments are not formatted so nice... if you cannot read to I can include it to the answere. – Dániel Kis Oct 22 '16 at 20:15
  • when you try to print a Course and any other object, the Java tries to convert to to string. If an object has a toString overrided method it will be called if not than the parent object (Object) toString method will be called. – Dániel Kis Oct 22 '16 at 20:20
  • I haven't studied the @Override like this but it did work perfect. Thanks so much for your help!! – cccstudent Oct 22 '16 at 20:32
  • @Override means to override super class method. If you not extends any class than Object class will be extended, it has a toString method() – Dániel Kis Oct 22 '16 at 20:34