【发布时间】:2015-03-18 15:22:07
【问题描述】:
package Books;
import java.util.*;
class Book{
private int isbn;
private String title;
private static int count=0;
public Book(){
count ++;
}
public void readBook(){
int isbn=0;
Scanner input = new Scanner(System.in);
String temp;
Book book = new Book();
System.out.print("ISBN: ");
temp=input.nextLine();
book.setIsbn(Integer.parseInt(temp));
System.out.print("title: ");
String title = input.nextLine();
book.setTitle(title);
}
public int getCount(){
return count;
}
public void incrCount(){
this.count++;
}
public int getIsbn() {
return isbn;
}
public void setIsbn(int isbn) {
this.isbn = isbn;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
还有主要的:
package Books;
import java.io.IOException;
import java.util.Scanner;
/**
*
* @author Ionut
*/
public class Books {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException, NumberFormatException{
Scanner input = new Scanner(System.in);
Book book = new Book();
int choice;
Book[] books = new Book[10];
int currentIndex;
String temp;
for (int i = 0; i < books.length; i++) {
books[i] = new Book();
}
while(true){
do{
System.out.println("Library System");
System.out.println(" 1. add book");
System.out.println(" 2. display books");
System.out.println(" 3. save to file");
System.out.println(" 4. load from file");
System.out.println(" 0. exit");
System.out.print("choice: ");
temp = input.nextLine();
choice = Integer.parseInt(temp);
}while ((choice < 0) || (choice > 4));
switch (choice){
case 1: //read isbn, title
currentIndex=book.getCount();
book.readBook();
//add current book to the array
books[currentIndex+1] = book;
book.incrCount();
break;
case 2: //display array of books
currentIndex=book.getCount();
System.out.println("ISBN Title ");
for(int i=0; i< currentIndex; i++){
System.out.println(books[i].getIsbn()+" "+books[i].getTitle()+" ");
}
break;
case 3: break;
case 4: break;
case 0: return ;
}
}//end while true
}
}
在我介绍的主要内容中 `
for (int i = 0; i < books.length; i++) {
books[i] = new Book();
}
` 现在我不再收到 NullPointerException 错误,但我收到了 ArrayIndexOutOfBoundsException。
run:
Library System
1. add book
2. display books
3. save to file
4. load from file
0. exit
choice: 1
ISBN: 1
title: 1
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 12
at Books.Books.main(Books.java:49)
Java Result: 1
BUILD SUCCESSFUL (total time: 5 seconds)
非常感谢任何帮助。 我不明白为什么会出现这个错误,我刚刚初始化了数组,为什么它会越界?
【问题讨论】:
-
您尝试访问
books[12]的地方。这是不正确的,因为你的数组有 10 长。您是否尝试调试此代码?你在 Books.java 中的第 49 行是什么? -
第49行是:books[currentIndex+1] = book;当他遇到那条线时,我的程序在案例 1 结束时“死亡”。
-
好的。所以
currentIndex将是 11。count在你的Book类中说,它被阅读了多少次?如何索引数组?您是否尝试调试此代码?如果没有,请尝试调试它!放一个断点,看看currentIndex的值! -
当我按下调试按钮时,我得到这个:调试:错误:无法找到或加载主类书籍。书籍 Java 结果:1 构建成功(总时间:0 秒)。
标签: java indexoutofboundsexception