2013-11-26 59 views
-2

我是java新手,所以請原諒我的無知。我正在開發一個將記錄寫入MySQL數據庫的項目。我得到一個空指針異常錯誤。我無法弄清楚我做錯了什麼。以下是代碼:MySQL數據庫寫入期間的空指針異常

package studentrecord; 


import java.io.PrintStream; 
import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.ResultSet; 
import java.sql.SQLException; 
import java.sql.Statement; 
import java.util.HashMap; 
import java.util.Map; 
import java.util.Scanner; 
import java.util.logging.Level; 
import java.util.logging.Logger; 

public class StudentRecord { 

    private Scanner in = new Scanner(System.in); 
    private PrintStream out = System.out; 
    private Map<Integer, Student> students = new HashMap<Integer, Student>(); 
    private Map<String, Mentor> mentors = new HashMap<String, Mentor>(); 

    private static Connection connection = null; 

    /** 
    * @return the connection 
    */ 
    public static Connection getConnection() { 
     return connection; 
    } 

    static { 
     // Create a connection to the registrar database 
     String url = "jdbc:mysql://localhost:3306/registrar"; 
     String userName = "root"; 
     String password = "Stef1234"; 

     try { 
      // Register the JDBC driver for MySQL. 
      Class.forName("com.mysql.jdbc.Driver"); 
      connection = DriverManager.getConnection(url, userName, password); 
      System.out.println("** CONNECTED TO DATABASE **"); 
     } catch (Exception ex) { 
      Logger.getLogger(StudentRecord.class.getName()).log(Level.SEVERE, null, ex); 
     } 
    } 

    class InvalidStudentException extends Exception { 

     @Override 
     public String toString() { 
      return "** INVALID STUDENT **"; 
     } 
    } 

    class NoStudentsFoundException extends Exception { 

     @Override 
     public String toString() { 
      return "** NO STUDENTS FOUND **"; 
     } 
    } 

    class InvalidMentorException extends Exception { 

     @Override 
     public String toString() { 
      return "** INVALID MENTOR **"; 
     } 
    } 

    class NoMentorsFoundException extends Exception { 

     @Override 
     public String toString() { 
      return "** NO MENTORS FOUND **"; 
     } 
    } 

    /** 
    * Load in students from the database. 
    */ 
    public StudentRecord() { 
     try { 
      Statement statement = connection.createStatement(); 
      ResultSet results = statement.executeQuery("SELECT * FROM student"); 

      // Read in each student from the results 
      int numStudents = 0; 
      while (results.next()) { 
       int studentID = results.getInt("studentID"); 
       String firstName = results.getString("firstName"); 
       String lastName = results.getString("lastName"); 

       // Attempt to determine what type of student this is 
       if (!results.getString("level").isEmpty()) {     // undergraduate 
        students.put(studentID, new Undergraduate(firstName, lastName, studentID)); 
       } else if (!results.getString("thesisTitle").isEmpty() || 
          !results.getString("thesisAdvisor").isEmpty()) { // graduate 
        students.put(studentID, new Graduate(firstName, lastName, studentID)); 
       } else if (!results.getString("company").isEmpty()) {  // part-time 
        students.put(studentID, new PartTime(firstName, lastName, studentID)); 
       } else { 
        out.println("** UNKNOWN STUDENT TYPE: (" + studentID + ") " 
           + firstName + ", " + lastName + " **"); 
        continue; 
       } 

       ++numStudents; 
      } 

      statement.close(); 

      System.out.println("** LOADED " + numStudents + " STUDENTS **"); 
     } catch (SQLException ex) { 
      Logger.getLogger(PartTime.class.getName()).log(Level.SEVERE, null, ex); 
     } 
    } 

    public void run() { 
     // Display menu options 
     while (true) { 
      System.out.print("\nStudent Record Managing System\n" 
        + "==============================\n" 
        + "1) Add Student\n" 
        + "2) Delete Student\n" 
        + "3) Query Student\n" 
        + "4) Update Student\n" 
        + "5) Add Mentor\n" 
        + "6) Query Mentor\n" 
        + "7) Exit\n\n" 
        + "Enter Option: "); 

      // Do the correct action 
      try { 
       switch (Integer.parseInt(in.nextLine())) { 
        case 1: 
         addStudent(); 
         break; 
        case 2: 
         deleteStudent(); 
         break; 
        case 3: 
         queryStudent(); 
         break; 
        case 4: 
         updateStudent(); 
         break; 
        case 5: 
         addMentor(); 
         break; 
        case 6: 
         queryMentor(); 
         break; 
        case 7: 
         cleanup(); 
         return; 
       } 
      } catch (Exception e) { 
       out.println(e.toString()); 
      } 
     } 
    } 

    /** 
    * Adds a student. 
    */ 
    private void addStudent() { 
     out.println(); 

     out.print("Enter First Name: "); 
     String firstName = in.nextLine(); 

     out.print("Enter Last Name: "); 
     String lastName = in.nextLine(); 

     out.print("Enter ID: "); 
     int ID = Integer.parseInt(in.nextLine()); 

     int option; 
     do { 
      out.print("Select Status (1 = Resident, 2 = Non-Resident): "); 
      option = Integer.parseInt(in.nextLine()); 
     } while (!(option == 1 || option == 2)); 
     Student.Status status = option == 1 ? Student.Status.Resident : Student.Status.NonResident; 

     int type; 
     do { 
      out.print("Select Type (1 = Undergraduate, 2 = Graduate, 3 = Part-Time): "); 
      type = Integer.parseInt(in.nextLine()); 
     } while (type < 1 || type > 3); 

     // Request additional attributes depending on student type 
     Student student = null; 
     switch (type) { 
      case 1: // undergraduate 
       int levelOption; 
       do { 
        out.print("Select Level: (1 = Freshman, 2 = Sophomore, 3 = Junior, 4 = Senior): "); 
        levelOption = Integer.parseInt(in.nextLine()); 
       } while (levelOption < 1 || levelOption > 4); 
       Undergraduate.Level level = levelOption == 1 ? Undergraduate.Level.Freshman 
         : levelOption == 2 ? Undergraduate.Level.Sophomore 
         : levelOption == 3 ? Undergraduate.Level.Junior 
         : Undergraduate.Level.Senior; 

       student = new Undergraduate(firstName, lastName, ID, status, level); 
       break; 
      case 2: // graduate 
       out.print("Enter Thesis Title: "); 
       String thesisTitle = in.nextLine(); 

       out.print("Enter Thesis Advisor: "); 
       String thesisAdvisor = in.nextLine(); 

       student = new Graduate(firstName, lastName, ID, status, thesisTitle, thesisAdvisor); 
       break; 
      case 3: // part-time 
       in.nextLine(); 
       out.print("Enter Company: "); 
       String company = in.nextLine(); 

       student = new PartTime(firstName, lastName, ID, status, company); 
       break; 
     } 

     // Add the student to both the internal map and the database 
     students.put(ID, student); 
     student.add(); 
     out.println("** STUDENT ADDED **"); 
    } 

    /** 
    * Selects a student from the current list of students. 
    * @return 
    * @throws StudentRecord.NoStudentsFoundException 
    * @throws StudentRecord.InvalidStudentException 
    */ 
    private int selectStudent() throws NoStudentsFoundException, InvalidStudentException { 
     // If there are no students, throw an exception 
     if (students.size() == 0) { 
      throw new NoStudentsFoundException(); 
     } 

     // Display all the available students 
     out.println("\nList of students\n" 
       + "================"); 
     for (Student s : students.values()) { 
      out.printf("(%d) %s %s\n", s.getStudentID(), s.getFirstName(), s.getLastName()); 
     } 

     out.print("\nEnter ID: "); 
     int ID = Integer.parseInt(in.nextLine()); 

     if (!students.containsKey(ID)) { 
      throw new InvalidStudentException(); 
     } 

     return ID; 
    } 

    /** 
    * Selects a mentor from the current list of mentors. 
    * @return 
    * @throws StudentRecord.NoMentorsFoundException 
    * @throws StudentRecord.InvalidMentorException 
    */ 
    private String selectMentor() throws NoMentorsFoundException, InvalidMentorException { 
     // If there are no mentors, throw an exception 
     if (mentors.size() == 0) { 
      throw new NoMentorsFoundException(); 
     } 

     // Display all the available mentors 
     out.println("\nList of mentors\n" 
       + "==============="); 
     for (Mentor m : mentors.values()) { 
      out.printf("%s %s\n", m.getFirstName(), m.getLastName()); 
     } 

     out.print("\nEnter Full Name: "); 
     String fullName = in.nextLine(); 

     if (!mentors.containsKey(fullName)) { 
      throw new InvalidMentorException(); 
     } 

     return fullName; 
    } 

    /** 
    * Deletes a student. 
    * @throws StudentRecord.NoStudentsFoundException 
    * @throws StudentRecord.InvalidStudentException 
    */ 
    private void deleteStudent() throws NoStudentsFoundException, InvalidStudentException { 
     int index = selectStudent(); 
     students.get(index).delete(); 
     students.remove(index); 
     out.println("** STUDENT DELETED **"); 
    } 

    /** 
    * Display a student's information. 
    * @throws StudentRecord.NoStudentsFoundException 
    * @throws StudentRecord.InvalidStudentException 
    */ 
    private void queryStudent() throws NoStudentsFoundException, InvalidStudentException { 
     students.get(selectStudent()).query(); 
    } 

    /** 
    * Updates a student's information. 
    * @throws StudentRecord.NoStudentsFoundException 
    * @throws StudentRecord.InvalidStudentException 
    */ 
    private void updateStudent() throws NoStudentsFoundException, InvalidStudentException { 
     Student student = students.get(selectStudent()); 

     // Generate base menu 
     String menu = "\nUpdate\n" 
       + "======\n" 
       + "1) GPA\n" 
       + "2) Status\n"; 

     // Add additional attributes to the menu depending on type of student 
     if (student instanceof Undergraduate) { 
      menu += "3) Level\n"; 
     } else if (student instanceof Graduate) { 
      menu += "3) Thesis Title\n" 
        + "4) Thesis Advisor\n"; 
     } else if (student instanceof PartTime) { 
      menu += "3) Company\n"; 
     } 

     menu += "\nEnter Choice: "; 
     out.print(menu); 

     switch (Integer.parseInt(in.nextLine())) { 
      case 1: 
       out.print("Enter GPA: "); 
       student.setGPA(Float.parseFloat(in.nextLine())); 
       break; 
      case 2: 
       int option; 
       do { 
        out.print("Select Status (1 = Resident, 2 = Non-Resident): "); 
        option = Integer.parseInt(in.nextLine()); 
       } while (!(option == 1 || option == 2)); 
       Student.Status status = option == 1 ? Student.Status.Resident : Student.Status.NonResident; 
       student.setStatus(status); 
       break; 
      case 3: 
       if (student instanceof Undergraduate) { 
        int levelOption; 
        do { 
         out.print("Select Level: (1 = Freshman, 2 = Sophomore, 3 = Junior, 4 = Senior): "); 
         levelOption = Integer.parseInt(in.nextLine()); 
        } while (levelOption < 1 || levelOption > 4); 
        ((Undergraduate) student).setLevel(levelOption == 1 ? Undergraduate.Level.Freshman 
          : levelOption == 2 ? Undergraduate.Level.Sophomore 
          : levelOption == 3 ? Undergraduate.Level.Junior 
          : Undergraduate.Level.Senior); 
       } else if (student instanceof Graduate) { 
        out.print("Enter Thesis Title: "); 
        ((Graduate) student).setThesisTitle(in.nextLine()); 
       } else if (student instanceof PartTime) { 
        out.print("Enter Company: "); 
        ((PartTime) student).setCompany(in.nextLine()); 
       } 
       break; 
      case 4: 
       if (!(student instanceof Graduate)) { 
        out.println("** INVALID CHOICE **"); 
       } 

       out.print("Enter Thesis Advisor: "); 
       ((Graduate) student).setThesisAdvisor(in.nextLine()); 
       break; 
      default: 
       out.println("** INVALID CHOICE **"); 
       return; 
     } 

     student.update(); 
     out.println("** STUDENT UPDATED **"); 
    } 

    /** 
    * Adds a mentor. 
    */ 
    private void addMentor() { 
     out.println(); 

     out.print("Enter First Name: "); 
     String firstName = in.nextLine(); 

     out.print("Enter Last Name: "); 
     String lastName = in.nextLine(); 

     Mentor mentor = new Mentor(firstName, lastName); 

     out.print("\nAdd Students\n" 
       + "============\n"); 
     for (Student s : students.values()) { 
      out.printf("(%d) %s %s\n", s.getStudentID(), s.getFirstName(), s.getLastName()); 
     } 
     out.print("Enter a list of IDs (separated by commas): "); 
     String[] ids = in.nextLine().split(","); 
     for (String ID : ids) { 
      try { 
       mentor.addStudent(students.get(Integer.parseInt(ID))); 
      } catch (Exception e) { 
      } 
     } 


     mentors.put(firstName + ' ' + lastName, mentor); 
     out.println("** MENTOR ADDED **"); 
    } 

    /** 
    * Displays the mentor's information and his list of students. 
    * @throws StudentRecord.NoMentorsFoundException 
    * @throws StudentRecord.InvalidMentorException 
    */ 
    private void queryMentor() throws NoMentorsFoundException, InvalidMentorException { 
     out.println("\n\nMentor Info\n" 
       + "============\n" 
       + mentors.get(selectMentor()).toString()); 
    } 

    /** 
    * Cleans up resources. 
    */ 
    private void cleanup() { 
     if (getConnection() != null) { 
      try { 
       getConnection().close(); 
      } catch (SQLException ex) { 
       Logger.getLogger(StudentRecord.class.getName()).log(Level.SEVERE, null, ex); 
      } 
     } 
    } 

    public static void main(String[] args) { 
     StudentRecord manager = new StudentRecord(); 
     manager.run(); 
    } 
} 

Student.java:

package studentrecord; 

/** 
* 
* @author Gwen 
*/ 

import java.sql.Connection; 



public abstract class Student { 
    private String firstName; 
    private String lastName; 
    private String mentor; 
    private int studentID; 
    private float GPA; 
    protected Connection connection = StudentRecord.getConnection(); 

    /** 
    * @return the firstName 
    */ 
    public String getFirstName() { 
     return firstName; 
    } 

    /** 
    * @return the lastName 
    */ 
    public String getLastName() { 
     return lastName; 
    } 

    /** 
    * @return the mentor 
    */ 
    public String getMentor() { 
     return mentor; 
    } 

    /** 
    * @param mentor the mentor to set 
    */ 
    public void setMentor(String mentor) { 
     this.mentor = mentor; 
    } 

    /** 
    * @return the studentID 
    */ 
    public int getStudentID() { 
     return studentID; 
    } 

    /** 
    * @param GPA the GPA to set 
    */ 
    public void setGPA(float GPA) { 
     this.GPA = GPA; 
    } 

    /** 
    * @return the GPA 
    */ 
    public double getGPA() { 
     return GPA; 
    } 

    /** 
    * @return the status 
    */ 
    public Status getStatus() { 
     return status; 
    } 

    /** 
    * @param status the status to set 
    */ 
    public void setStatus(Status status) { 
     this.status = status; 
    } 

    public enum Status { Resident, NonResident }; 
    private Status status; 

    /** 
    * Creates a student. 
    * @param firstName 
    * @param lastName 
    * @param studentID 
    * @param mentor 
    * @param status 
    * @param GPA 
    */ 
    public Student(String firstName, String lastName, int studentID) { 
     this(firstName, lastName, studentID, Status.NonResident); 
    } 

    /** 
    * Creates a student. 
    * @param firstName 
    * @param lastName 
    * @param studentID 
    * @param mentor 
    * @param status 
    * @param GPA 
    */ 
    public Student(String firstName, String lastName, int studentID, Status status) { 
     this.firstName = firstName; 
     this.lastName = lastName; 
     this.studentID = studentID; 
     this.mentor = ""; 
     this.GPA = 4.f; 
    } 

    /** 
    * Calculates the tuition for the student. 
    * @param creditHours the number of credit hours the student has 
    * @return 
    */ 
    public abstract double calculateTuition(int creditHours); 

    /** 
    * Updates the database entry for the student 
    */ 
    public abstract void update(); 

    /** 
    * Creates the database entry for the student 
    */ 
    public abstract void add(); 

    /** 
    * Deletes the database entry for the student 
    */ 
    public abstract void delete(); 

    /** 
    * Queries the database for the student's information 
    * and prints it to the screen 
    */ 
    public abstract void query(); 

    @Override 
    public String toString() { 
     return "First Name: " + firstName + '\n' + 
       "Last Name: " + lastName + '\n' + 
       "Student ID: " + studentID + '\n' + 
       "Status: " + status.toString() + '\n' + 
       "Mentor: " + mentor + '\n' + 
       "GPA: " + GPA; 
    } 
} 

任何援助將不勝感激!謝謝!!

+5

你面臨NPE的哪種說法? – Masudul

+1

並請顯示堆棧跟蹤。 – home

+0

這裏是輸出:** **連接到數據庫** **加載0學生** 學生檔案管理系統 ===================== ========= 1)添加學生 2)刪除學生 3)的查詢學生 4)更新學生 5)添加導師 6)的查詢導師 7)退出 輸入選項:1 輸入名字:J 輸入姓氏:B 輸入識別號碼:1 選擇狀態(1 =居民,2 =非居民):1 Sele ct類型(1 =本科,2 =研究生,3 =兼職):1 選擇等級:(1 =新生,2 =大二,3 =初級,4 =高級):1 java.lang.NullPointerException' – user3037102

回答

0

檢查ResultSet.getString的文檔:
http://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html#getString%28int%29

字符串的getString(INT columnIndex)拋出的SQLException

返回: 列值;如果該值爲SQL NULL,則返回值爲空

根據這個代碼是脆弱的null pointer exception在以下地點:

if (!results.getString("level").isEmpty()) {     
    ....... 
    } else if (!results.getString("thesisTitle").isEmpty() || 
      !results.getString("thesisAdvisor").isEmpty()) { 
    .......... 
    } else if (!results.getString("company").isEmpty()) {  
    ............ 

如果這些列中包含空值,那麼getString(..)返回null,並因此getString(...).isEmpty()返回null pointer exception