Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 8 of 8

Thread: Multiple nullpointerexceptions in my code.

  1. #1
    Junior Member
    Join Date
    Oct 2011
    Posts
    3
    My Mood
    Stressed
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Multiple nullpointerexceptions in my code.

    I thought I had this working but I'm getting nullpointerexceptions now on lines 21,31, & 80. I think I've been looking at it for too long.
    Can someone help me out?

     
    1 package student;
    2
    3 import java.sql.Connection;
    4 import java.sql.ResultSet;
    5 import java.sql.Statement;
    6 import java.util.HashMap;
    7 import java.util.Map.Entry;
    8 import java.util.Scanner;
    9
    10 public class StudentApp {
    11 private HashMap<String, Mentor> mapMentors = new HashMap<String, Mentor>();
    12 private HashMap<Integer, Student> mapStudents = new HashMap<Integer, Student>();
    13
    14 private int maxID = 0;
    15 private Scanner scan = new Scanner(System.in);
    16
    17 /**
    18 * @param args the command line arguments
    19 */
    20 public static void main(String[] args) {
    21 new StudentApp().run();
    22 }
    23
    24 /**
    25 * Run the app
    26 */
    27 private void run() {
    28 System.out.println("\tStudent Database System");
    29 int cmd;
    30
    31 init();
    32
    33 while ((cmd = getMenu()) != 9)
    34 {
    35 switch (cmd)
    36 {
    37 case 1:
    38 addStudent();
    39 break;
    40 case 2:
    41 updateStudent();
    42 break;
    43 case 3:
    44 deleteStudent();
    45 break;
    46 case 4:
    47 queryStudent();
    48 break;
    49 case 5:
    50 calculateTuition();
    51 break;
    52 case 6:
    53 createMentor();
    54 break;
    55 case 7:
    56 assignMentor();
    57 break;
    58 case 8:
    59 listAll();
    60 break;
    61 default:
    62 System.out.println("Unknown command.");
    63 break;
    64 }
    65 System.out.print("Press enter to continue...");
    66 scan.nextLine();
    C:/Users/jwhite/Desktop/Student/src/student/StudentApp.java
    1.1 of 7 2011.10.23 20:27:45
    66 scan.nextLine();
    67
    68 }
    69 System.out.println("\nThanks for using the system.");
    70 }
    71
    72 /**
    73 * Init the database
    74 */
    75 private void init() {
    76 try
    77 {
    78 Student.connect();
    79 Connection con = Student.getConnection();
    80 Statement stmt = con.createStatement();
    81 ResultSet rs = stmt.executeQuery("select * from student");
    82 do {
    83 if (!rs.next())
    84 break;
    85 int id = rs.getInt("studentID");
    86 String fname = rs.getString("firstName").trim();
    87 String lname = rs.getString("lastName").trim();
    88 double gpa = rs.getDouble("gpa");
    89 String status = rs.getString("status").trim();
    90 String mentor = rs.getString("mentor").trim();
    91 String level = rs.getString("level").trim();
    92 String thesisTitle = rs.getString("thesisTitle").trim();
    93 String thesisAdvisor = rs.getString("thesisAdvisor").trim();
    94 String company = rs.getString("company").trim();
    95
    96 if (id > maxID)
    97 maxID = id;
    98
    99 Student st;
    100 if (!level.isEmpty())
    101 st = new Undergraduate(fname, lname, id, gpa, status, mentor, level);
    102 else if (!company.isEmpty())
    103 st = new PartTime(fname, lname, id, gpa, status, mentor, company);
    104 else
    105 st = new Graduate(fname, lname, id, gpa, status, mentor, thesisTitle, thesisAdvisor);
    106 mapStudents.put(id, st);
    107
    108 if (!mentor.isEmpty()) {
    109 String[] names = mentor.split(" ");
    110 String mfname = "";
    111 String mlname = "";
    112 if (names != null && names.length > 0)
    113 mfname = names[0];
    114 if (names != null && names.length > 1)
    115 mlname = names[1];
    116 Mentor mt;
    117 if (!mapMentors.containsKey(mentor)) {
    118 mt = new Mentor(mfname, mlname);
    119 mapMentors.put(mentor, mt);
    120 }
    121 else
    122 mt = mapMentors.get(mentor);
    123 mt.addStudent(st);
    124 }
    125 } while (!rs.isLast());
    126 } catch (Exception e)
    127 {
    128 e.printStackTrace();
    129 }
    130 }
    131
    132 /**
    C:/Users/jwhite/Desktop/Student/src/student/StudentApp.java
    2.1 of 7 2011.10.23 20:27:45
    132 /**
    133 * Display the user menu and return the choice.
    134 *
    135 */
    136 private int getMenu() {
    137 System.out.println();
    138 System.out.println("1. Add a student.");
    139 System.out.println("2. Update a student.");
    140 System.out.println("3. Delete a student.");
    141 System.out.println("4. Query a student");
    142 System.out.println("5. Calculate tuition");
    143 System.out.println("6. Create a mentor ");
    144 System.out.println("7. Add students to a mentor");
    145 System.out.println("8. List all");
    146 System.out.println("9 . Exit");
    147 System.out.print("Enter your choice: ");
    148 // skip non integer
    149 while (!scan.hasNextInt())
    150 scan.next();
    151 int cmd = scan.nextInt();
    152 scan.nextLine(); // skip others.
    153 return cmd;
    154 }
    155
    156 /**
    157 * Add the new student
    158 */
    159 private void addStudent() {
    160 System.out.print("Enter the stduentID: ");
    161 while (!scan.hasNextInt())
    162 scan.next();
    163 int id = scan.nextInt();
    164 scan.nextLine();
    165 if (mapStudents.containsKey(id)) {
    166 System.out.println("Student already exists");
    167 return;
    168 }
    169 System.out.print("Choose the type:\n1=Undergraduate 2=Grauate 3=PartTime: ");
    170 int type = 0;
    171 Student st;
    172 do {
    173 while (!scan.hasNextInt())
    174 scan.next();
    175 type = scan.nextInt();
    176 scan.nextLine();
    177 } while (type < 0 || type > 3);
    178 if (type == 1)
    179 st = new Undergraduate();
    180 else if (type == 2)
    181 st = new Graduate();
    182 else
    183 st = new PartTime();
    184 st.setStudentID(id);
    185 readStudent(st);
    186 st.add();
    187 mapStudents.put(id, st);
    188 }
    189
    190 /**
    191 * Update the student
    192 */
    193 private void updateStudent() {
    194 Student st = getStudent();
    195 if (st == null) {
    196 System.out.println("Cannot find the student.");
    197 }
    198 else {
    C:/Users/jwhite/Desktop/Student/src/student/StudentApp.java
    3.1 of 7 2011.10.23 20:27:45
    198 else {
    199 readStudent(st);
    200 st.update();
    201 }
    202 }
    203
    204 /**
    205 * Read student information from the user
    206 */
    207 private void readStudent(Student st) {
    208 System.out.print("Enter the first name: ");
    209 st.setFirstName(scan.next());
    210 scan.nextLine(); // skip
    211 System.out.print("Enter the last name: ");
    212 st.setLastName(scan.next());
    213 scan.nextLine();
    214 System.out.print("Enter the GPA: ");
    215 while (!scan.hasNextDouble())
    216 scan.next();
    217 st.setGPA(scan.nextDouble());
    218 scan.nextLine();
    219 System.out.print("Choose the status(1=resident, other=nonresident): ");
    220 while (!scan.hasNextInt())
    221 scan.next();
    222 if (scan.nextInt() == 1)
    223 st.setStatus("resident");
    224 else
    225 st.setStatus("nonresident");
    226 scan.nextLine();
    227
    228 if (st instanceof Graduate) {
    229 Graduate gst = (Graduate)st;
    230 System.out.print("Enter the thesisTitle: ");
    231 gst.setThesisTitle(scan.nextLine());
    232 System.out.print("Enter the thesisAdvisor: ");
    233 gst.setThesisAdvisor(scan.nextLine());
    234 }
    235 else if (st instanceof Undergraduate) {
    236 Undergraduate ust = (Undergraduate)st;
    237 System.out.print("Choose the leve:\n 1=freshman, 2=sophomore, 3=junior, 4=senior: ");
    238 int id = 0;
    239 do {
    240 while (!scan.hasNextInt())
    241 scan.next();
    242 id = scan.nextInt();
    243 scan.nextLine();
    244 } while (id < 0 || id > 4);
    245 if (id == 1)
    246 ust.setLevel("freshman");
    247 else if (id == 2)
    248 ust.setLevel("sophomore");
    249 else if (id == 3)
    250 ust.setLevel("junior");
    251 else if (id == 4)
    252 ust.setLevel("senior");
    253 }
    254 else if (st instanceof PartTime) {
    255 PartTime pst = (PartTime)st;
    256 System.out.print("Enter the company: ");
    257 pst.setCompany(scan.nextLine());
    258 }
    259 }
    260 /**
    261 * Delete the student
    262 */
    263 private void deleteStudent() {
    C:/Users/jwhite/Desktop/Student/src/student/StudentApp.java
    4.1 of 7 2011.10.23 20:27:45
    264 Student st = getStudent();
    265 if (st == null) {
    266 System.out.println("Cannot find the student.");
    267 }
    268 else {
    269 String mname = st.getMentor();
    270 Mentor mt = mapMentors.get(mname);
    271 if (mt != null)
    272 mt.removeStudent(st);
    273 mapStudents.remove(st.getStudentID());
    274 st.delete();
    275 }
    276 }
    277
    278 /**
    279 * Query a student
    280 */
    281 private void queryStudent() {
    282 Student st = getStudent();
    283 if (st == null) {
    284 System.out.println("Cannot find the student.");
    285 }
    286 else {
    287 st.query();
    288 }
    289 }
    290
    291 /**
    292 * Calculate the tuition of a student
    293 */
    294 private void calculateTuition() {
    295 Student st = getStudent();
    296 if (st == null) {
    297 System.out.println("Cannot find the student.");
    298 return;
    299 }
    300 System.out.print("Enter the hours: ");
    301 while (!scan.hasNextInt())
    302 scan.next();
    303 int hours = scan.nextInt();
    304 scan.nextLine();
    305 double value = st.calculateTuition(hours);
    306 System.out.printf("The tuition is %.2f\n", value);
    307 }
    308
    309 /**
    310 * Create a new Mentor
    311 */
    312 private void createMentor() {
    313 Mentor mt = getMentor(true);
    314 if (mt == null) {
    315 System.out.println("Failed: The Mentor exists.");
    316 return;
    317 }
    318
    319 System.out.println(mt);
    320 System.out.println("New Mentor added!");
    321 String name = (mt.getFirstName() + " " + mt.getLastName()).trim();
    322 mapMentors.put(name, mt);
    323 }
    324
    325 /**
    326 * Assign a student to a mentor
    327 */
    328 private void assignMentor() {
    329 Mentor mt = getMentor(false);
    C:/Users/jwhite/Desktop/Student/src/student/StudentApp.java
    5.1 of 7 2011.10.23 20:27:45
    329 Mentor mt = getMentor(false);
    330 if (mt == null) {
    331 System.out.println("Cannot find The Mentor.");
    332 return;
    333 }
    334 Student st = getStudent();
    335 if (st == null) {
    336 System.out.println("Cannot find the student.");
    337 return;
    338 }
    339 String oldmname = st.getMentor();
    340 Mentor oldmt = mapMentors.get(oldmname);
    341 if (oldmt != null)
    342 oldmt.removeStudent(st);
    343
    344 mt.addStudent(st);
    345 st.update();
    346 }
    347
    348 /**
    349 * Query and return a Mentor
    350 * @param newMentor true : create a new Mentor
    351 * false : query from the list
    352 * @return Mentor object
    353 */
    354 private Mentor getMentor(boolean newMentor) {
    355 System.out.println("Enter the name of the mentor:");
    356 System.out.print("Enter the first name: ");
    357 String fname = scan.nextLine();
    358 System.out.print("Enter the last name: ");
    359 String lname = scan.nextLine();
    360 String name = (fname + " " + lname).trim();
    361 for (Entry<String, Mentor> m : mapMentors.entrySet()) {
    362 Mentor mt = m.getValue();
    363 String mname = (mt.getFirstName() + " " + mt.getLastName()).trim();
    364
    365 if (mname.equals(name)) {
    366 if (newMentor)
    367 return null;
    368 return mt;
    369 }
    370 }
    371 if (newMentor)
    372 return new Mentor(fname, lname);
    373 return null;
    374 }
    375
    376 /**
    377 * Query for a student
    378 * @return student object
    379 */
    380 private Student getStudent() {
    381 System.out.print("Enter the stduentID: ");
    382 while (!scan.hasNextInt())
    383 scan.next();
    384 int id = scan.nextInt();
    385 scan.nextLine();
    386 return mapStudents.get(id);
    387 }
    388
    389 /**
    390 * List all the mentors and the students
    391 */
    392 private void listAll() {
    393 for (Entry<String, Mentor> m : mapMentors.entrySet()) {
    394 System.out.println(m.getValue().toString());
    395 System.out.println();
    C:/Users/jwhite/Desktop/Student/src/student/StudentApp.java
    6.1 of 7 2011.10.23 20:27:45
    395 System.out.println();
    396 }
    397 System.out.println("Students Without Mentor");
    398 for (Entry<Integer, Student> s : mapStudents.entrySet()) {
    399 if (s.getValue().getMentor().isEmpty()) {
    400 System.out.println(s.getValue().toString());
    401 System.out.println();
    402 }
    403 }
    404 System.out.println("Total " + mapMentors.size() + " Mentor(s)");
    405 System.out.println("Total " + mapStudents.size() + " Student(s)");
    406
    407 }
    408
    409 }


  2. #2
    Grand Poobah
    Join Date
    Mar 2011
    Posts
    1,545
    My Mood
    Grumpy
    Thanks
    0
    Thanked 167 Times in 158 Posts

    Default Re: Multiple nullpointerexceptions in my code.

    79 Connection con = Student.getConnection();
    80 Statement stmt = con.createStatement();

    The only thing on line 80 that could be null is con. Therefore on line 79 Student.getConnection must be returning null. Add a print statement in between to print out con. If it is null then you need to find out why getConnection is returning null.
    Improving the world one idiot at a time!

  3. #3
    Think of me.... Mr.777's Avatar
    Join Date
    Mar 2011
    Location
    Pakistan
    Posts
    1,136
    My Mood
    Grumpy
    Thanks
    20
    Thanked 82 Times in 78 Posts
    Blog Entries
    1

    Default Re: Multiple nullpointerexceptions in my code.

    Student.connect();
    What is processed in connect()?

    Post your Student class code here too, so we could hav a look over it.

  4. #4
    Junior Member
    Join Date
    Oct 2011
    Posts
    3
    My Mood
    Stressed
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Multiple nullpointerexceptions in my code.

     
     
    1 package student;
    2
    3 import java.sql.Connection;
    4 import java.sql.DriverManager;
    5
    6 public abstract class Student {
    7 protected String firstName;
    8 protected String lastName;
    9 protected int studentID;
    10 protected double GPA;
    11 protected String status; // resident or nonresident
    12 protected String mentor;
    13
    14 protected static Connection dbCon;
    15
    16 /**
    17 * Default constructor
    18 */
    19 Student() {
    20 firstName = "";
    21 lastName = "";
    22 studentID = 0;
    23 GPA = 0;
    24 status = "resident";
    25 mentor = "";
    26 }
    27
    28 /**
    29 * Paramter Constructor
    30 * @param firstName
    31 * @param lastName
    32 * @param studentID
    33 */
    34 Student(String firstName, String lastName, int studentID) {
    35 this.firstName = firstName;
    36 this.lastName = lastName;
    37 this.studentID = studentID;
    38 this.GPA = 0;
    39 this.status = "resident";
    40 this.mentor = "";
    41 }
    42
    43 /**
    44 * Parameter Constructor 2
    45 * @param firstName
    46 * @param lastName
    47 * @param studentID
    48 * @param gpa
    49 * @param status
    50 * @param mentor
    51 */
    52 Student(String firstName, String lastName, int studentID, double gpa, String status, String mentor) {
    53 this.firstName = firstName;
    54 this.lastName = lastName;
    55 this.studentID = studentID;
    56 this.GPA = gpa;
    57 this.status = status;
    58 this.mentor = mentor;
    59 }
    60
    61 /**
    62 * Return the database connection.
    63 */
    64 public static Connection getConnection() {
    65 return dbCon;
    66 }
    67
    68 /**
    69 * Connect the database
    70 */
    71 public static void connect() {
    72 try {
    73 Class.forName("com.mysql.jdbc.Driver");
    74 if (dbCon != null)
    75 dbCon.close();
    76 dbCon = DriverManager.getConnection("jdbc:mysql://localhost:3306/registrar",
    77 "root", "555680");
    78 } catch (Exception e) {
    79 e.printStackTrace();
    80 }
    81 }
    82
    83 /**
    84 * Calculate the tuition
    85 * @param hours Number of credit hours
    86 * @return the tuition
    87 */
    88 public abstract double calculateTuition(int hours);
    89
    90 /**
    91 * Update the student record in the database
    92 */
    93 public abstract boolean update();
    94
    95 /**
    96 * Add the student record to the database
    97 */
    98 public abstract boolean add();
    99
    100 /**
    101 * Delete the record in the database
    102 */
    103 public abstract boolean delete();
    104
    105 /**
    106 * Retrieve the record from the database
    107 */
    108 public abstract boolean query();
    109
    110 @Override
    111 /**
    112 * Return the String representation of the Student
    113 */
    114 public String toString() {
    115 String s = "Student Name: " + firstName + " " + lastName + "\n";
    116 s += "ID: " + studentID + "\n";
    117 s += "GPA: " + GPA + "\n";
    118 s += "Status: " + status + "\n";
    119 s += "Mentor: " + mentor + "\n";
    120 return s;
    121 }
    122
    123 // Getters and Setters
    124 public String getFirstName() {
    125 return firstName;
    126 }
    127
    128 public void setFirstName(String firstName) {
    129 this.firstName = firstName;
    130 }
    131
    132 public String getLastName() {
    133 return lastName;
    134 }
    135
    136 public void setLastName(String lastName) {
    137 this.lastName = lastName;
    138 }
    139
    140 public int getStudentID() {
    141 return studentID;
    142 }
    143
    144 public void setStudentID(int studentID) {
    145 this.studentID = studentID;
    146 }
    147
    148 public double getGPA() {
    149 return GPA;
    150 }
    151
    152 public void setGPA(double gpa) {
    153 GPA = gpa;
    154 }
    155
    156 public String getStatus() {
    157 return status;
    158 }
    159
    160 public void setStatus(String status) {
    161 this.status = status;
    162 }
    163
    164 public String getMentor() {
    165 return mentor;
    166 }
    167
    168 public void setMentor(String mentor) {
    169 this.mentor = mentor;
    170 }
    171
    172 }

  5. #5
    Think of me.... Mr.777's Avatar
    Join Date
    Mar 2011
    Location
    Pakistan
    Posts
    1,136
    My Mood
    Grumpy
    Thanks
    20
    Thanked 82 Times in 78 Posts
    Blog Entries
    1

    Default Re: Multiple nullpointerexceptions in my code.

    Why don't you try
    java.sql.Statement stmt=con.createStatement();
    instead of
    Statement stmt = con.createStatement();


    EDIT: A suggestion, i will recommend you, not to use static connection, as it can take your system resources and can cause performance issues. If you used it coz of not to open connection, everytime, you must see connection pools that just keep opening multiple connections and use them only when it is needed. So, creating a static connection is highly discouraged.
    Last edited by Mr.777; November 2nd, 2011 at 12:16 AM.

  6. #6
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,318
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: Multiple nullpointerexceptions in my code.

    Quote Originally Posted by Mr.777 View Post
    Why don't you try
    java.sql.Statement stmt=con.createStatement();
    instead of
    Statement stmt = con.createStatement();
    I'm not sure how an explicit import - something that affects compilation - would rectify a NullPointerException at runtime.

    javastudnt, does the connection actually get established? The client has no checks to verify the connection is actually created, and if not the return connection will be null. You should redesign how the connection is established and how exceptions are thrown and caught. For example, make use of the try/catch/finally - have the connect method throw the exception, and force the client to catch the exception - in which case the client knows the error occurred and can deal with it accordingly, as well as close the connection in the finally clause if all is well. Moving onto things like connection pools as mr777 pointed out is something to keep in mind

  7. #7
    Junior Member
    Join Date
    Oct 2011
    Posts
    3
    My Mood
    Stressed
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Multiple nullpointerexceptions in my code.

    Thanks for the insight!
    Let me go back and reevaluate with a fresh point of view and see what I can do.

  8. #8
    Think of me.... Mr.777's Avatar
    Join Date
    Mar 2011
    Location
    Pakistan
    Posts
    1,136
    My Mood
    Grumpy
    Thanks
    20
    Thanked 82 Times in 78 Posts
    Blog Entries
    1

    Default Re: Multiple nullpointerexceptions in my code.

    Quote Originally Posted by copeg View Post
    I'm not sure how an explicit import - something that affects compilation - would rectify a NullPointerException at runtime.
    I know that it will not make any difference, yet i guess, may be, 1 out of 100

Similar Threads

  1. Multiple Problems
    By ZeroLRS in forum What's Wrong With My Code?
    Replies: 6
    Last Post: August 16th, 2011, 07:33 AM
  2. Multiple Multishuffles
    By dino2dy in forum What's Wrong With My Code?
    Replies: 3
    Last Post: November 10th, 2010, 01:36 PM
  3. multiple tcp connection?
    By nasser in forum Java Networking
    Replies: 4
    Last Post: July 31st, 2010, 07:35 AM
  4. Multiple Queues
    By fh84 in forum Threads
    Replies: 1
    Last Post: December 3rd, 2009, 02:28 PM
  5. Which interface gives more control on serialization of an object?
    By abhishekraok2003 in forum Java Theory & Questions
    Replies: 1
    Last Post: May 16th, 2009, 10:17 AM