简体   繁体   中英

Why is my program throwing an exception?

Whats happening is when I try to add a new class to my student, I have to check to make sure that the class time I am trying to add doesn't conflict with my students other class times, but for some reason when the code gets into the loop to check the other course times stored in an array list, there is an exeption called when their shouldn't be. For example, I could put in 5:00p-10:00p for one course, then 1:00p-2:00p for the second course and it will throw the exception like there is a conflict there when there isn't. please check the comment to see where the problem occurs. any ideas?

package myschool;

import java.util.ArrayList;
import java.util.Scanner;

public class MySchool {
private static Exception e;

public static void main(String[] args) {

    ArrayList<Student> listStudent = new ArrayList<>();
    ArrayList<Integer> listCourseStart = new ArrayList<>();
    ArrayList<Integer> listCourseEnd = new ArrayList<>();

    boolean continueLoop = true;
    boolean addFirstCourse = true;
    boolean addACourse = false;
    Scanner userInput = new Scanner(System.in);

    int option;

    do{
    try {  
    System.out.println(" What would you like to do?");
    System.out.println(" 1) Add a student");
    System.out.println(" 2) View students");
    System.out.println(" 3) Remove a student");
    System.out.println(" 4) Exit");
    System.out.print("--> ");
    option = userInput.nextInt();

    switch( option ){
            case 1:
                Scanner inputs = new Scanner(System.in);
                String fName, lName;
                int sID;
                double sGPA;

                System.out.print(" First Name:");
                fName = inputs.nextLine();

                System.out.print(" Last Name:");
                lName = inputs.nextLine();

                System.out.print(" ID Number:");
                sID = inputs.nextInt();

                System.out.print(" GPA:");
                sGPA = inputs.nextDouble();

                Student newStudent = new Student(fName, lName, sID, sGPA);
                listStudent.add(newStudent);

                inputs.nextLine();

                while (true) {
                    try {
                        System.out.println("Would you like to add a course? Y/N");
                        String shouldAddCourse = inputs.nextLine();

                        if( "N".equals(shouldAddCourse.toUpperCase()))
                                       break;

                        System.out.print(" CourseName:");
                        String cName = inputs.nextLine();

                        System.out.print(" Instructor:");
                        String instructor = inputs.nextLine();

                        System.out.print(" CourseID:");
                        int cID = inputs.nextInt();

                        System.out.print(" CourseCredit:");
                        int cCred = inputs.nextInt();
                        inputs.nextLine();

                        System.out.print(" StartTime:");
                        String cStart = inputs.nextLine();
                        System.out.print(" AM or PM ?");
                        String startAMorPM = inputs.nextLine();

                        System.out.print(" EndTime:");
                        String cEnd = inputs.nextLine();
                        System.out.print(" AM or PM ?");
                        String endAMorPM = inputs.nextLine();

                        String cStartRemove = cStart.replace(":","");
                        int startInt = Integer.parseInt( cStartRemove );

                        String cEndRemove = cEnd.replace(":","");
                        int endInt = Integer.parseInt( cEndRemove );

                        if( "PM".equals(startAMorPM) || "pm".equals(startAMorPM) || "P".equals(startAMorPM) || "p".equals(startAMorPM) )
                            startInt = startInt + 1200;

                        if( "PM".equals(endAMorPM) || "pm".equals(endAMorPM) || "P".equals(endAMorPM) || "p".equals(endAMorPM) )
                            endInt = endInt + 1200;

                        if( addFirstCourse ){
                            Course newCourse = new Course( cName, instructor, cCred, cStart, cEnd, cID );
                            newStudent.listCourse.add(newCourse);
                            listCourseStart.add( startInt );
                            listCourseEnd.add( endInt );
                            addFirstCourse = false;
                        }else{     

                        for( Integer r: listCourseStart ) {
                            if( startInt >= listCourseStart.get(r) && startInt <= listCourseEnd.get(r) /*|| endInt >= listCourseStart.get(r) && endInt <= listCourseEnd.get(r)*/ ) //the problems happens hear on the first listCourseStart.get(r)
                                throw e;
                            else
                                addACourse = true;
                        }

                        if( addACourse == true ){
                            listCourseStart.add( startInt );
                            listCourseEnd.add( endInt );
                            Course newCourse = new Course( cName, instructor, cCred, cStart, cEnd, cID );
                            newStudent.listCourse.add(newCourse);
                            addACourse = false;
                            }
                        }

                    } catch (Exception e) {
                        System.out.println("You have already added a class at that time!");
                    }
                }
                break;


            case 2:
                if(!listStudent.isEmpty()){
                    for(Student l:listStudent) {
                        System.out.println(l);
                        for(Course n:l.listCourse) {
                            System.out.println(n);
                        }
                        System.out.println();
                    }


                }else
                System.out.println("There are no students to view\n");

               break;

            case 3:
                Scanner removeChoice = new Scanner(System.in);

                try {
                    if(!listStudent.isEmpty()){
                    int j = 0;
                    System.out.println("Which student do you want to remove?");

                        for(Student l:listStudent) {
                            System.out.print(j+1 + ")");
                            System.out.println(l);
                            j++;
                        }
                        int remove = removeChoice.nextInt();
                            listStudent.remove( remove - 1 );
                        System.out.println("Student has been removed\n");
                    }else
                        System.out.println("There are no students to remove\n");

                } catch (Exception e) {
                    System.out.println("There are no students to remove\n");
                }

                break;

            case 4:
                continueLoop = false;
                break;
    }
    } catch (Exception e) {
        System.out.println("That is not a valid option!!!");
        continueLoop = false;
    }

    }while( continueLoop );
}

}

You're throwing an exception in your for loop.

for( Integer r: listCourseStart ) {
    if( startInt >= listCourseStart.get(r) && startInt <= listCourseEnd.get(r) /*|| endInt >= listCourseStart.get(r) && endInt <= listCourseEnd.get(r)*/ ) //the problems happens hear on the first listCourseStart.get(r)
        throw e;// <-- This guy is the culprit, but I'm guessing you already knew that...
    else
        addACourse = true;
}

It's fairly difficult to say exactly where it's going wrong (it's a bit hard to read your code, but it should be behaving as you've stated).

You may want to use some breakpoints, if you're using an IDE, and check the values of your input variables before they get put into the list, or have it spit them back out at you on the command line, before putting them in the list.

I think the problem is your loop

for( Integer r: listCourseStart ) { // r ist the value in listCourseStart
    // you use the value 'r' as index
    // you have to use for( int i = 0; i.....) or 'r' is the the right value
    if( startInt >= listCourseStart.get(r) && startInt <= listCourseEnd.get(r) ) 
        throw e;
    else
        addACourse = true;
}

Try this

for( Integer r: listCourseStart ) {
    if( startInt >= r && startInt <= r ) 
        throw e;
    else
        addACourse = true;
}

EDIT:

Yout are right in your comment. Your condition is not necessary. You need to store the start and end time together. Here is an exsample:

List<Integer[]> times = new ArrayList<>();
times.add(new Integer[]{900,1100});
times.add(new Integer[]{1300,1400});
for( Integer[] time : times ){
    if( startInt >= time[0] && startInt <= time[1] 
         || endInt >= time[0] && endInt <= time[1] ){
        throw e;
    }
}

A little Hint: Your Exception e was never initiate - you will get a NullPointerException

You are misusing the list listCourseStart in the for loop.

for( Integer r: listCourseStart ) {
  if( startInt >= listCourseStart.get(r) && startInt <= listCourseEnd.get(r) )                                     
    throw e;
  else
    addACourse = true;
}

listCourseStart is a list of intergers and with

for( Integer r: listCourseStart ) {
  // ...
}

you iterate over the list elements. So in the first iteration r will be the first list element, in the second iteration the second list element and so on.

But inside your loop you call listCourseStart.get(r) . The list's get() method retrieves the list element at the given position. So if the first list element is 5 then with listCourseStart.get(5) you get the fifth list element. I'm sure, this is not really what you want.

Why didn't you use a debugger? You can run your program step by step, it shows you the actual variable values so you can see what's going on in detail.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM