2013-04-01 8 views
3

학교 프로젝트를 계속 진행하고 있으며 다른 오류가 발생한 것으로 보입니다. 그래서 무슨 일이 벌어지고 기본적으로 코드가 괜찮아 보이는 경우에도 널 포인터 예외를 받고있다. 내 배열에 문제가 있다고 생각합니다. 심지어 몇 시간 동안 검색해도 오류를 찾을 수없는 것 같습니다. 다시 한번, 어떤 도움/솔루션이라도 대단히 감사하겠습니다.배열 널 포인터 예외 오류

import java.util.*; 

public class library { 

private static students stu1 = new students(65435, "Bob", "Ted"); 
private static students stu2 = new students(45546, "Guy", "Sid"); 
private static students stu3 = new students(78688, "Tim", "Cas"); 
private static students stu4 = new students(45387, "Guy", "Jim"); 
private static students stu5 = new students(12367, "Dom", "Lam"); 
private static students stu6 = new students(45905, "Kid", "Loo"); 
private static students stu7 = new students(65484, "Mut", "Hum"); 
private static students stu8 = new students(34578, "Kim", "Hay"); 
private static students stu9 = new students(20457, "Roy", "Boy"); 
private static students stu0 = new students(15678, "Kil", "Bil"); 

private static students[] studentArray; 
private static students[] stuArrayAlt; 
private static boolean firstArrayStu = true; 

// private static books bookName = new books("title", 
// "author","category","isbn", cost, rating out of 10); 

private static books book1 = new books(
     "Harry Potter and the Deathly Hallows", "JK Rowling", "fantasy", 
     "9780739360385", 30.00, 9.0); 
private static books book2 = new books("Angels and Demons", "Dan Brown", 
     "fiction", "9780828855495", 25.00, 8.5); 
private static books book3 = new books("The Hunger Games", 
     "Suzanne Collins", "science fiction", "9780439023481", 20.00, 8.0); 
private static books book4 = new books("A Game of Thrones", 
     "George R R Martin", "fantasy", "9780002245845", 54.50, 12.5); 
private static books book5 = new books("title2", "author2", "category2", 
     "isbn2", 54.50, 12.5); 
private static books book6 = new books("title2", "author2", "category2", 
     "isbn2", 54.50, 12.5); 
private static books book7 = new books("title2", "author2", "category2", 
     "isbn2", 54.50, 12.5); 
private static books book8 = new books("title2", "author2", "category2", 
     "isbn2", 54.50, 12.5); 
private static books book9 = new books("title2", "author2", "category2", 
     "isbn2", 54.50, 12.5); 
private static books book0 = new books("title2", "author2", "category2", 
     "isbn2", 54.50, 12.5); 

private static books[] bookArray; 
private static books[] bookArrayAlt; 
private static boolean firstArrayBook; 

private static int year1; 
private static int month1; 
private static int date1; 

public library() { 
    bookArray = new books[] { book1, book2, book3, book4, book5, book6, 
      book7, book8, book9, book0 }; 
    firstArrayBook = true; 

    studentArray = new students[] { stu1, stu2, stu3, stu4, stu5, stu6, 
      stu7, stu8, stu9, stu0 }; 
    firstArrayStu = true; 
} 

public static void main(String[] args) { 
    // System.out.println(stu1.getStuNum() + " " + stu1.getFirstName() + 
    // " "+ stu1.getLastName()); 

    // books[] bookReturn = stu1.insertBook(book1); 
    // System.out.println(book1.getCheckInLibrary()); 
    // System.out.println(book1.getCheckInLibrary()); 

    // System.out.println(bookReturn[0].getName()); 

    // books[] bookReturn2 = stu1.insertBook(book2); 
    // System.out.println(book2.getCheckInLibrary()); 
    // System.out.println(book2.getCheckInLibrary()); 
    // stu1.insertBook(book1); 

    // checkOutBook(stu1,book1); 
    // System.out.println(stu1); 
    // stu1=null; 
    // System.out.println(stu1); 

    /* 
    * stu1.lostBookFine(book1); System.out.println(stu1.getFineBalance()); 
    * stu1.lostBookFine(book2); System.out.println(stu1.getFineBalance()); 
    */ 

    int[] a = new int[] { 1, 2, 3, 4, 5 }; 
    int[] b = new int[(a.length) + 1]; 

    System.arraycopy(a, 0, b, 0, a.length); 
    b[a.length] = 6; 
    // for(int i=0;i<b.length;i++) 
    // { 
    // System.out.println(b[i]); 
    // } 

    /* 
    * int[] c = new int[]{1,2,3,4,5,6}; b = new int[(c.length)+1]; 
    * 
    * System.arraycopy(c, 0, b, 0, c.length); b[c.length]=7; 
    * 
    * for(int i=0;i<b.length;i++) { System.out.println(b[i]); } 
    */ 

    // int[] date = enterDate(); 
    // int[] date2 = book1.addTwoWeeks(date); 
    // int[]date2= book1.getDateDue(); 

    System.out.println(studentArray[0].getFirstName()); 

    //boolean array=checkStuNum(45456); 
    //System.out.println(array); 

    //students[]array=lookUpLastName("sid"); 
    //array[0].getFirstName(); 

} 

public static void returnBook(students borrower, books bookReturn) { 

} 

public static books[] lookUpTitleBooks(String title)// //////////////interchange 
                // the array-boolean 
                // firstArrayBook--two 
                // if statements 
{ 

    int counter = 0; 
    for (int i = 0; i < bookArray.length; i++) { 
     if (title.equalsIgnoreCase(bookArray[i].getTitle()) 
       || ((bookArray[i].getTitle().toLowerCase())).contains(title 
         .toLowerCase())) { 
      counter++; 
     } 
    } 
    books[] booksLookUp = new books[counter]; 
    int counterS = 0; 
    for (int i = 0; i < bookArray.length; i++) { 
     if (title.equalsIgnoreCase(bookArray[i].getTitle()) 
       || ((bookArray[i].getTitle().toLowerCase())).contains(title 
         .toLowerCase())) { 
      booksLookUp[counterS] = bookArray[i]; 
      counterS++; 
     } 
    } 

    return booksLookUp; 
} 

// look up last name of student 
public static students[] lookUpLastName(String lName) { 

    students[] studentlName = new students[1] ; 

    if (firstArrayStu == true) { 
     int counter = 0; 
     System.out.println("check"); 
     for (int i = 0; i < studentArray.length; i++) { 
      if (lName.equalsIgnoreCase(studentArray[i].getLastName()) || ((studentArray[i].getLastName()).contains(lName.toLowerCase()))){ 
       counter++; 
       System.out.println("check if"); 

      } 
      System.out.println("check for"); 

     } 
     studentlName = new students[counter]; 
     int counterS = 0; 
     for (int i = 0; i < studentArray.length; i++) { 
      if (lName.equalsIgnoreCase(studentArray[i].getFirstName()) 
        || ((studentArray[i].getFirstName().toLowerCase())) 
          .contains(lName.toLowerCase())) { 
       studentlName[counterS] = studentArray[i]; 
       counterS++; 
      } 
     } 
    } 

    if (firstArrayStu == false) { 
     int counter = 0; 
     for (int i = 0; i < stuArrayAlt.length; i++) { 
      if (lName.equalsIgnoreCase(stuArrayAlt[i].getFirstName()) 
        || ((stuArrayAlt[i].getFirstName().toLowerCase())) 
          .contains(lName.toLowerCase())) { 
       counter++; 
      } 
     } 
     studentlName = new students[counter]; 
     int counterS = 0; 
     for (int i = 0; i < stuArrayAlt.length; i++) { 
      if (lName.equalsIgnoreCase(stuArrayAlt[i].getFirstName()) 
        || ((stuArrayAlt[i].getFirstName().toLowerCase())) 
          .contains(lName.toLowerCase())) { 
       studentlName[counterS] = stuArrayAlt[i]; 
       counterS++; 
      } 
     } 
    } 

    return studentlName; 
} 

public static void checkOutBook(students borrower, books bookBorrow) { 

    boolean canBorrow1 = checkFine(borrower); 
    boolean canBorrow2 = checkBorrowedBooks(borrower); 
    boolean canBorrow3 = checkBorrowedBooks(bookBorrow); 

    if (canBorrow1 == false) { 
     System.out.println("Your fine is too damn high");// alert window and 
                  // redirect to 
                  // main menu-so 
                  // he/she can 
                  // pay it if he 
                  // wants to 
    } 
    if (canBorrow2 == false) { 
     System.out.println("Your already have 3 books checked out");// alert 
                    // window 
                    // and 
                    // redirect 
                    // to 
                    // main 
                    // menu- 
                    // so 
                    // he/she 
                    // can 
                    // return 
                    // a 
                    // book 
                    // if he 
                    // wants 
                    // to 
    } 
    if (canBorrow1 == false) { 
     System.out.println("This book has been checkd out");// alert window 
                  // and redirect 
                  // to main menu- 
                  // so he/she can 
                  // look for 
                  // another book 
                  // and check it 
                  // out 
    } 
    if (canBorrow1 && canBorrow2 && canBorrow3) { 
     borrower.insertBook(bookBorrow); 
     bookBorrow.checkOutStatusChange(); 
     // alert window to show successful check out and redirect to main 
     // menu 
    } 

} 

public static boolean checkFine(students borrower) { 
    boolean canBorrow1 = borrower.checkBorrowedBooks(borrower 
      .getBookArray()); 
    return canBorrow1; 
} 

public static boolean checkBorrowedBooks(students borrower) { 
    boolean canBorrow2 = borrower.checkFine(borrower); 
    return canBorrow2; 
} 

public static boolean checkBorrowedBooks(books bookBorrow) { 
    boolean canBorrow3 = bookBorrow.getCheckInLibrary(); 
    return canBorrow3; 
} 

public static int[] enterDate() { 
    Scanner input = new Scanner(System.in); 
    boolean dateTrue = false; 

    int year, month, date; 

    while (dateTrue == false) { 

     System.out.println("Enter year"); 
     year = input.nextInt(); 

     System.out.println("Enter month"); 
     month = input.nextInt(); 

     System.out.println("Enter date"); 
     date = input.nextInt(); 

     // checking first date---------------------------------------- 
     year1 = ((year >= 2010) ? year : 0); 

     month1 = ((month >= 1 && month <= 12) ? month : 0); 

     if (month1 == 1) { 
      date1 = ((date >= 1 && date <= 31) ? date : 0); 
     } 

     if (month1 == 2 && (year1 % 4) != 0) { 
      date1 = ((date >= 1 && date <= 28) ? date : 0); 
     } 

     if (month1 == 2 && (year1 % 4) == 0) { 
      date1 = ((date >= 1 && date <= 29) ? date : 0); 
     } 

     if (month1 == 3) { 
      date1 = ((date >= 1 && date <= 31) ? date : 0); 
     } 

     if (month1 == 4) { 
      date1 = ((date >= 1 && date <= 30) ? date : 0); 
     } 

     if (month1 == 5) { 
      date1 = ((date >= 1 && date <= 31) ? date : 0); 
     } 

     if (month1 == 6) { 
      date1 = ((date >= 1 && date <= 30) ? date : 0); 
     } 

     if (month1 == 7) { 
      date1 = ((date >= 1 && date <= 31) ? date : 0); 
     } 

     if (month1 == 8) { 
      date1 = ((date >= 1 && date <= 31) ? date : 0); 
     } 

     if (month1 == 9) { 
      date1 = ((date >= 1 && date <= 30) ? date : 0); 
     } 

     if (month1 == 10) { 
      date1 = ((date >= 1 && date <= 31) ? date : 0); 
     } 

     if (month1 == 11) { 
      date1 = ((date >= 1 && date <= 30) ? date : 0); 
     } 

     if (month1 == 12) { 
      date1 = ((date >= 1 && date <= 31) ? date : 0); 
     } 

     if (month1 == 0 || date1 == 0 || year1 == 0) { 
      // do nothing boolean remains false 
      // put alert window here 
     } else { 
      dateTrue = true; 
     } 
    } 

    int[] dates = { year1, month1, date1 }; 
    return dates; 
} 

public void createStudent(int stuNum, String fName, String lName) { 
    if (firstArrayStu == true) { 

     for (int i = 0; i < studentArray.length; i++) { 
      if (studentArray[i] == null) { 
       studentArray[i] = new students(stuNum, fName, lName); 

      } else if (i == (studentArray.length - 1)) { 
       stuArrayAlt = new students[studentArray.length + 1]; 
       System.arraycopy(studentArray, 0, stuArrayAlt, 0, 
         studentArray.length); 
       stuArrayAlt[studentArray.length] = new students(stuNum, 
         fName, lName); 
       firstArrayStu = false; 
      } 
     } 

    } else if (firstArrayStu == false) { 
     for (int i = 0; i < stuArrayAlt.length; i++) { 
      if (stuArrayAlt[i] == null) { 
       stuArrayAlt[i] = new students(stuNum, fName, lName); 

      } else if (i == (stuArrayAlt.length - 1)) { 
       studentArray = new students[stuArrayAlt.length + 1]; 
       System.arraycopy(stuArrayAlt, 0, stuArrayAlt, 0, 
         stuArrayAlt.length); 
       studentArray[stuArrayAlt.length] = new students(stuNum, 
         fName, lName); 
       firstArrayStu = true; 
      } 
     } 
    } 
} 

public static void createBook(String name, String author, String category, 
     String isbn, double cost, double sRating) { 

    if (firstArrayBook == true) { 
     for (int i = 0; i < bookArray.length; i++) { 
      if (bookArray[i] == null) { 
       bookArray[i] = new books(name, author, category, isbn, 
         cost, sRating); 

      } else if (i == (bookArray.length - 1)) { 
       bookArrayAlt = new books[bookArray.length + 1]; 
       System.arraycopy(bookArray, 0, bookArrayAlt, 0, 
         bookArray.length + 1); 
       bookArrayAlt[bookArray.length] = new books(name, author, 
         category, isbn, cost, sRating); 
       firstArrayBook = false; 
      } 
     } 
    } 

    else if (firstArrayBook == false) { 
     for (int i = 0; i < bookArrayAlt.length; i++) { 
      if (bookArrayAlt[i] == null) { 
       bookArrayAlt[i] = new books(name, author, category, isbn, 
         cost, sRating); 

      } else if (i == (bookArrayAlt.length - 1)) { 
       bookArray = new books[bookArrayAlt.length + 1]; 
       System.arraycopy(bookArrayAlt, 0, bookArray, 0, 
         bookArrayAlt.length + 1); 
       bookArray[bookArrayAlt.length] = new books(name, author, 
         category, isbn, cost, sRating); 
       firstArrayBook = false; 
      } 
     } 
    } 
} 

public static boolean deleteStudent(String lName, int stuNum) { 
    students[] arrayLookedUp = lookUpLastName(lName); 
    boolean deleted = false; 
    for (int i = 0; i < arrayLookedUp.length; i++) { 
     if ((arrayLookedUp[i].getStuNum()) == stuNum) { 
      System.out.println("checker"); 
      if (firstArrayStu == true) { 
       for (int j = 0; j < studentArray.length; j++) { 
        if (arrayLookedUp[i] == studentArray[j]) { 
         studentArray[j] = null; 
         deleted = true; 
         break; 
        } 
       } 
       break; 

      } else if (firstArrayStu == false) { 
       for (int j = 0; j < stuArrayAlt.length; j++) { 
        if (arrayLookedUp[i] == stuArrayAlt[j]) { 
         stuArrayAlt[j] = null; 
         deleted = true; 
         break; 
        } 
       } 
      } 
     } else if (i == (arrayLookedUp.length - 1)) { 
      deleted = false; 
     } 
    } 

    return deleted; 
} 

public static boolean checkStuNum(int stuNum) { 

    // private static students[] studentArray; 
    // private static students[] stuArrayAlt; 
    // private static boolean firstArrayStu=true; 
    boolean stuNumNew = false; 

    System.out.println("test"); 
    if (firstArrayStu == true) { 
     for (int i = 0; i < studentArray.length; i++) { 
      System.out.println("false"); 

      if ((studentArray[i].getStuNum()) == stuNum) { 
       System.out.println("true"); 

       stuNumNew = true; 

       break; 
      } 
     } 
    } 

    else if (firstArrayStu == false) { 
     for (int i = 0; i < stuArrayAlt.length; i++) { 
      if ((stuArrayAlt[i].getStuNum()) == stuNum) { 
       stuNumNew = true; 

       break; 
      } 
     } 
    } 

    return stuNumNew; 
} 

}

나는 생성자와 학생 클래스 및

public String getFirstName() { 
     return fName; 
    } 

하지만 아직도 내가 오류를 얻고을 명시하는 방법이있다. 나는 많은 코드가 있다는 것을 알고 있습니다. 다시 한번 어떤 종류의 도움이라도 대단히 감사 할 것입니다. 코드가 현재 기록으로

+0

어디에서 오류가 발생합니까? 즉, 스택 트레이스는 어떤 라인을 가리 킵니까? (그리고 오류 메시지를 붙여 넣는 것도 도움이 될 것입니다.) – iamnotmaynard

+0

null 포인터 예외 인 log cat의 행 번호를 확인하십시오. –

+0

예외 스택 추적을 여기에서 지나치십시오! –

답변

8

, 당신은 결코 배열을 초기화하지하고 있기 때문에

System.out.println(studentArray[0].getFirstName()); 

가 NPE 발생합니다.

private static students[] studentArray; 

그냥 선언하고 초기화하지 않습니다. 당신이 배열이 아닌 목록을 사용하기 위해 최선을 다하고 경우

private static ArrayList<students> studentArray = new ArrayList<students>(); 

// Inside the constructor or some method called before you access studentArray: 
studentArray.add(stu1); 
studentArray.add(stu2); 
//... 

// or, more concisely, since you're not using the temporary `students` variables: 
studentArray.add(new students(65435, "Bob", "Ted")); 
studentArray.add(new students(45546, "Guy", "Sid")); 
//... 

을 다음과 같이

은 어쩌면 당신은,

private static students[] studentArray; 

요구에 코드를 리팩토링해야 할 것은

처럼 뭔가로 초기화한다
private static students[] studentArray = new students[10]; 

다음 요소를 할당해야합니다.

studentArray[0] = stu1; 

또는

studentArray[0] = new students(65435, "Bob", "Ted"); 
+0

사용하려고 제안했던 코드와 정확히 동일한 코드 줄을 사용하여 배열을 초기화했는데 어떤 이유로 여전히 작동하지 않습니다. – user2229592

+0

초기화하는 것만으로는 충분하지 않습니다. 참조하기 전에 요소에 값을 할당해야합니다. 제가 추가 한 마지막 두 줄을보십시오. – jedwards

4

당신은 항상 액세스하기 전에 객체를 생성해야합니다. 당신은 배열을 가리키는 참조 선언 :

private static students[] studentArray; 

을하지만, 참조 어떤 객체를 할당하지 않습니다. 따라서 NullPointerException이 발생합니다.

사용이 : 코드 위

private static students[] studentArray = new students[size]; 

는 참조 변수 (studentArray)가 가리키는 새로운 객체 (학생들의 배열)을 생성합니다. 또는

보다 효율적인 다음 배열 인 List 또는 Set을 사용할 수 있습니다.

+0

나는 당신이 말한대로 행동하지 않았습니다. 같은 오류. – user2229592

+0

bookArray 및 bookArrayAlt에 대해 동일한 실수를 범했습니다. 그들도 똑같이하십시오. 예외가 발생한 행을 확인하십시오. –