2013-12-20 2 views
0

У меня возникли проблемы с распечаткой деталей, которые были введены в мой массив. когда я запускаю свой addBook i в деталях из двух книг, но когда я выбираю вариант 2 из меню, я получаю ошибку времени выполнения (outofbounds), Выше разрешено путем добавления [i] к линии печати и изменения длины цикла.Ошибка при распечатке моего объекта из массива

Проблема, с которой я столкнулся, если мой BookID из моего кредитного портфеля, не увеличивая его.

import java.util.Scanner; 

public class library { 
    static Scanner keyboard = new Scanner(System.in); 
    static boolean run = true; 
    public static fiction [] fictionArray = new fiction[2]; 
    public static nonfiction [] nonfictionArray = new nonfiction[2]; 


    public static void main (String[] args){        // main class method 
     while (run){     // this while statement allows the menu to come up again 
      int answer = 0;    // answer initialized to Zero 
      boolean isNumber; 
      do{        // start of validation 
       System.out.println("1. Add book");  // Menu selections 
       System.out.println("2. Display the books available for loan"); 
       System.out.println("3. Display the books currently on loan"); 
       System.out.println("4. Make a book loan"); 
       System.out.println("5. Return book "); 
       System.out.println("6 Write book details to file"); 
       if (keyboard.hasNextInt()){      // I would like to set values to =>1 <=6 
        answer = keyboard.nextInt();     // this is more validation for the input for menu selection 
        isNumber = true; 
       } else {          // else if number not entered, it will prompt for the correct input 
        System.out.print(" You must enter a number from the menu to continue. \n"); 
        isNumber = false; 
        keyboard.next();        // clears keyboard 

       } 
      } 
      while (!(isNumber));          // while to continue program after the do has completed 
      switch (answer){           // switch statement - uses answer from the keyboard to select a case 

       case 1: 
        addBook();         // adds book 
        break; 
       case 2: 
        for (int i=0; i<5; i++){ 
        if (fictionArray[i] != null){ 
          System.out.println(fictionArray);} 
        if (nonfictionArray[i] != null){ 
         System.out.println(nonfictionArray);}} 

        break; 
       case 3: 
        break; 
       case 4: 
        break; 
       case 5: 
        break; 
       case 6: 
        break; 
      } 
     } 
    } 
     static void addBook(){ 
      loanbook [] loanArray = new loanbook[2]; 
      String title,author; 
      int choice; 
      for(int x = 0; x < loanArray.length; x++){ 
      System.out.print("Press 1 for Fiction or 2 for Non Fiction: "); // sub menu for fiction and non fiction 
      choice = keyboard.nextInt(); 
      if (choice == 1){ 
       for(int count = 0; count < fictionArray.length; count++){ 
        System.out.print("Enter title: "); 
        title= keyboard.nextLine(); 
        title= keyboard.nextLine(); 
        System.out.print("Enter author: "); 
        author= keyboard.nextLine(); 
        fictionArray[count] = new fiction(title, author); 
        System.out.println("The book information you entered was : " + fictionArray[count].toString()); // this will show the entry which was inout to the array 
        count++; }} 
      else if (choice == 2) { 
       for(int count = 0; count < nonfictionArray.length; count++){ 
        System.out.print("Enter title: "); 
        title= keyboard.nextLine(); 
        title= keyboard.nextLine(); 
        System.out.print("Enter author: "); 
        author= keyboard.nextLine(); 
        nonfictionArray[count] = new nonfiction(title, author); 
        System.out.println("The book information you entered was : " + nonfictionArray[count].toString()); // this will show the entry which was inout to the array 
        count++;}} 
      else{ int noBooks = loanArray.length; 
       for (int i=0; i<noBooks; i++){ 
        System.out.print(loanArray[x]); 
       }}}} // addbook 



} // Library end 

Ниже моя суперкласса, то мой подкласс

public class loanbook { 
    private String title,author; 
    private int bookID; 

    public loanbook(String pTitle,String pAuthor){ 
     bookID = 0; 
     title = pTitle; 
     author = pAuthor; 
     bookID++; 
    } // Constructor 
    public void setTitle(String pTitle){ 
     title = pTitle; 
    } // setTitle 
    protected String getTitle(){ 
     return title; 
    } // getTitle 
    protected String getAuthor(){ 
     return author; 
    } // getAuthor 
    public String toString(){ 
     return "\n BookID: "+ bookID+"\n" + " Title: "+ getTitle()+"\n" +" Author : "+ getAuthor()+ "\n"; 
    } 

} // loanbook 

Мои подклассы являются одинаковыми для имени класса и конструктор

public class fiction extends loanbook { 
    String bookType; 
    private String getBookType;  // Would be fiction 

    public fiction(String pTitle,String pAuthor){ 
     super(pTitle,pAuthor); 
    } // constructor 
    protected void setBookType (String pBookType){ 
     bookType = pBookType; 
    } // setter for bookType 

    protected String getBookType(){ 
     return "Fiction"; 
    } 
    public String toString(){ 
     return super.toString() +" This book is : "+ getBookType(); 
    } 
} // class 
+0

Пожалуйста, пост полный StackTrace вашей ошибки. Обратите внимание, что 'fictionarray' имеет длину 2, но вы повторяете его до 5 .. –

+0

И просто предложение: вы вообще не хотите ставить весь свой код в основном методе – Lucas

ответ

1

Две вещи, которые я вижу

if (fictionArray[i] != null){ 
    System.out.println(fictionArray);}   
if (nonfictionArray[i] != null){ 
    System.out.println(nonfictionArray);}} 

Вы пытаетесь напечатать весь массив System.out.println(fictionArray). Вы, вероятно, хотите System.out.println(fictionArray[i])

Кроме того, вы должны установить свои размеры массива до 5, если вы хотите, чтобы петли 5 раз

+0

Спасибо, это разрешило проблему, но теперь это печатает только одну книгу. он также не увеличивает идентификатор bookID из суперкласса – user2854120

+0

. Думаю, у меня есть ответ на ваш предыдущий вопрос. Я ответил с исправлением на идентификатор книги. Вы должны сделать его статичным. И объявите и инициализируйте его в 0. 'int bookID = 0;' Вытащите его из конструктора. Оставьте «bookID ++» –

+0

. Я не мог рассказать вам, почему он печатает только одну книгу. Вы код меня пугает :). Слишком много. –

2

кроме Вы объявили о своей fictionarray и nonfictionarray к быть длиной 2. Однако в вашем случае 2, вы зацикливаете 5 раз:

for (int i=0; i<5; i++){ 
    if (fictionArray[i] != null){ 

Изменить на 2. Возможно, вы изменили длину массива в объявлении, но забыли изменить итерацию цикла. В этом случае, вы можете просто использовать длину массива:

for (int i = 0; i < fictionArray.length; i++) { 

Кроме того, похоже, что вы хотите, чтобы распечатать конкретный элемент массива, а не сам массив:

System.out.println(fictionArray[i]); 

и также для nonfictionarray и класс nonfiction.

Смежные вопросы