2014-12-03 2 views
0

Почему этот код не вызывает ошибку, если пользователь вводит отрицательное число?Моя программа не поймает исключения

public class Lab12 { 

    public static void main(String[] args) { 

      Course[] course1 = courses(); 
      print(course1); 
    }//end main 

    public static Course[] courses() throws IllegalArgumentException{ 
     Scanner input = new Scanner(System.in); 
     System.out.println("How many courses?"); 
     int numCourses = input.nextInt(); 
     Course[] array = new Course[numCourses]; 
     int s = 0; 
     boolean b = true; 
     for(int i = 0; i<numCourses; i++){ 
      System.out.println("Enter the course title."); 
      String t = input.nextLine(); 
      t = input.nextLine(); 
      System.out.println("Enter the corresponding major."); 
      String m = input.nextLine(); 
      do{ 
       try{ 
       System.out.println("Enter the number of students taking this course."); 
       s = input.nextInt(); 
       b = false; 
      }//end try block 
      catch(IllegalArgumentException ex){ 
       System.out.println("Input error."+ 
      "\nPlese enter a positive number for students.");}//end catch 
      }while(b); 
//Right here I dont see why my try catch wont work 
      Course c = new Course(t,m,s); 
      array[i] = c; 
     }//end for loop 
     input.close(); 
     return array; 
}//end courses method 
    public static void print(Course[] c){ 
     for(int i = 0; i<c.length; i++){ 
     System.out.println("Course title: "+c[i].getTitle()+ 
       "\nMajor: "+c[i].getMajor()+ 
       "\nNumber of Students: "+c[i].getStudents()); 
     }//end for loop 
    }//end 
}//end lab12 

Вот класс, связанный с главным:

public class Course { 

    private String title; 
    private String major; 
    private int students; 

    public Course(String t, String m, int s){ 

     title = t; 
     major = m; 
     students = s; 
     if(students<0){ 
     throw new IllegalArgumentException("Wrong Argument."); 
     } 
//my instruction were to throw an exception in the constructor is this correct 
    }//end constructor method 
    public String getTitle(){ 
     return title; 
    }//end get title 
    public String getMajor(){ 
     return major; 
    }//end get major 
    public int getStudents(){ 
     return students; 
    }//end get students 
    public void setTitle(String t){ 
     title = t; 
    }//end set title 
    public void setMajor(String m){ 
     major = m; 
    }//end set major 
    public void setStudents(int s){ 
     students = s; 
    }//end set students 
}//end Class Course 
+0

Вы создаете объект 'Course' вне TRY/улова. Если вы переместите его внутри оператора 'try', то будет выведено' IllegalArgumentException'. – gcarvelli

+0

@ killermonkey50 Положите это как ответ! – nickdbush

ответ

0

Для того, чтобы поймать исключение в Java, вы должны окружить код , который бросает исключение в try/catch блоке.

Изменения основной for петли на что-то вроде этого:

for(int i = 0; i<numCourses; i++){ 
     System.out.println("Enter the course title."); 
     String t = input.nextLine(); 
     t = input.nextLine(); 
     System.out.println("Enter the corresponding major."); 
     String m = input.nextLine(); 

     // Need to declare the Course object outside of the do/while so that it stays 
     // in scope afterwards 
     Course c = null; 

     do{ 
      try{ 
       System.out.println("Enter the number of students taking this course."); 
       s = input.nextInt(); 
       b = false; 

       // Create the Course here so that the try/catch will correctly catch 
       // the IllegalArgumentException 
       c = new Course(t,m,s); 

      }//end try block 
      catch(IllegalArgumentException ex){ 
       System.out.println("Input error."+ 
       "\nPlease enter a positive number for students."); 
      }//end catch 
     } while(b); 

     array[i] = c; 

    }//end for loop 
Смежные вопросы