Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/391.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 模拟小型图书馆查询系统时的NumberFormatException_Java_Exception_Catalog - Fatal编程技术网

Java 模拟小型图书馆查询系统时的NumberFormatException

Java 模拟小型图书馆查询系统时的NumberFormatException,java,exception,catalog,Java,Exception,Catalog,我正试图输入一个模拟小型图书馆查询系统的程序,但我一直得到同样的错误 错误如下: 线程“main”java.lang.NumberFormatException中的异常:对于输入字符串:“10001 Emma” 位于java.lang.NumberFormatException.forInputString(未知源) 位于java.lang.Integer.parseInt(未知源) 位于java.lang.Integer.parseInt(未知源) 在assg4_user.BookDemo.r

我正试图输入一个模拟小型图书馆查询系统的程序,但我一直得到同样的错误

错误如下:

线程“main”java.lang.NumberFormatException中的异常:对于输入字符串:“10001 Emma” 位于java.lang.NumberFormatException.forInputString(未知源) 位于java.lang.Integer.parseInt(未知源) 位于java.lang.Integer.parseInt(未知源) 在assg4_user.BookDemo.readCatalog(BookDemo.java:51) 在assg4_user.BookDemo.main(BookDemo.java:20) 我不知道该怎么处理。如果代码运行正确,那么它将要求用户输入一个图书ID,如果它在目录中列出,那么它将输出标题、作者等。如果没有,它将运行“BookNotFoundException”类

以下是目录的文本文件:

图书ID------书名------------------ISBN------------------作者------------------小说/非小说
10001------艾玛-----------------0486406482-------奥斯汀-----------------F
12345------我的生活------0451526554------约翰逊------N
21444----生活是美丽的----1234567890----马林----F
11111----马语者----1111111111----埃文斯----F
下面是代码:

import java.io.*;
import java.util.*;

public class BookDemo {

    static String catalogFile = "C:\\Users\\John\\workspace\\DataStructuresAssingments\\catalog.txt";
    static Book[] bookArray = new Book[100];
    static int bookCount = 0;

    public static void main(String args[]) throws FileNotFoundException, IOException, BookNotFoundException {

        // Read Catalog
        readCatalog();

        System.out.println("Enter book id:");
        Scanner in = new Scanner(System.in);
        int bookId = Integer.parseInt(in.nextLine());
        while (bookId != 0) {
            bookSearch(bookArray, bookCount, bookId);
            bookId = Integer.parseInt(in.nextLine());

        }
        in.close();
    }

    /**
     * Reads catalog file using try-with-resources
     */
    private static void readCatalog() throws FileNotFoundException, IOException {
        String line;
        try (BufferedReader br = new BufferedReader(new FileReader(catalogFile));) {
            while ((line = br.readLine()) != null) {
                String[] str = line.split(" ");
                Book book = new Book(Integer.parseInt(str[0]), str[1], str[2], str[3], str[4].charAt(0));
                bookArray[bookCount] = book;
                bookCount++;
            }
        }
    }

    /**
     * Search Books
     */
    private static void bookSearch(Book[] bookArr, int bookCount, Integer bookId) throws BookNotFoundException {
        boolean found = false;
        for (int i = 0; i < bookCount; i++) {
            if (bookArr[i].getBookId().equals(bookId)) {
                System.out.println(bookArr[i]);
                found = true;
                break;
            }
        }

        if (!found) {
            throw new BookNotFoundException("Book ID:" + bookId + " Not Found!");
        }
    }
}

NumberFormatException是一个RuntimeException,因此如果没有显式处理它,它将“滑动”到您的正常异常处理。因此,用这样一个try-catch来包围您的parseInt

try {
    bookId = Integer.parseInt(in.nextLine());
} catch (NumberFormatException e) {
    throw new BookNotFoundException();
}

我不会给你完整的解决方案,也不会给你问题的逻辑。出现此错误是因为您试图将字符串解析为整数(
“10001 Emma”
Integer.parseInt(“1001”)
仅当传递的参数为int且不包含任何字符时才起作用

编辑

根据您的数据,您的
bookId
仅包含int数据。现在,如果要强制用户仅输入int数据,请将
a
替换为
b
以下部分:

(a)

(b)


对第27行执行相同操作:
bookId=Integer.parseInt(in.nextLine())

readCatalog
使用
parseInt
失败。要进行调试,请将参数打印到控制台的
parseInt
(在本例中为
str[0]
)。如果不是您所期望的,那么是时候打印整行内容,并开始试验Java的工作原理以及如何让它正确解析您的行。

输入文件中是否有选项卡?还是多个空间?也许你应该像这样拆分这些行:

            String[] str = line.split("\\s+");

我只能通过在
10001
后面添加一个选项卡来重现您的错误

10001⟶艾玛0486406482
作为制表符)

您被一个空格分割,因此
10001
Emma
不是两个元素,而是一个数组元素,当然,它不能作为整数进行解析

您可以通过一个或多个拆分来修复此问题。由于
split()
接受正则表达式,您只需编写以下代码:

String[] str = line.split("\\s+");

哦,还有一些事情:

  • Book
    类中的属性都以“Book”开头。通常不需要重复类名。因此,
    id
    name
    isbn
    authorLastName
    类别
    都可以
  • 您可以使用
    列表
    而不是数组。它更优雅,而且您不必在开始时声明尺寸。另外,不再需要
    bookCount
    变量,因为您可以使用
    bookArray.size()
    获取大小
  • 使用Java8,您可以使用函数式编程来搜索这本书

    private static void search(List<Book> books, Integer bookId) throws BookNotFoundException {
        boolean found = books.stream()
            .anyMatch(t -> {
                System.out.println(t);
                return Objects.equals(t.getBookId(), bookId);
            });
    
        if (!found) {
            throw new BookNotFoundException("Book ID: " + bookId + " Not Found!");
        }
    }
    
    private static void search(列表书籍,整数bookId)抛出BookNotFoundException{
    找到布尔值=books.stream()
    .anyMatch(t->{
    系统输出打印ln(t);
    返回Objects.equals(t.getBookId(),bookId);
    });
    如果(!找到){
    抛出new BookNotFoundException(“图书ID:+bookId+“未找到!”);
    }
    }
    

谢谢你的建议,但我还是遇到了同样的错误。我认为实际上他的文件包含如下数据:
10001 Emma 0486406482 Austen F
不是
10001-------Emma---------------------------------------0486406482-------Austen------------------F
,因为他在assg4用户.BookDemo.main的第20行出现错误:
(BookDemo.java:20)
虽然在这种情况下不允许使用空格。如果是这种情况,“10001”将干净地解析,而不是包含“Emma”。事实上我们只是不知道,调试过程正是我在尝试执行某项操作时处理类似意外行为的方式。如果文件包含
10001------Emma---------------------0486406482------奥斯汀-----F
他会得到如下异常:
线程“main”中的异常java.lang.NumberFormatException:对于输入字符串:“10001-----Emma------------------0486406482------奥斯汀-----F”
不仅仅是
线程“main”中的异常java.lang.NumberFormatException:对于输入字符串:“10001 Emma”
。他也在这里请求输入rt?如果我用文件中的空格替换所有出现的一个或多个破折号,并删除标题行,我就可以了。。
int bookId;

    while(true)
    {
        try
        {
            bookId = Integer.parseInt(in.nextLine());
        }catch(NumberFormatException e)
        {
            System.out.println("Only integer input is accepted.");
            continue;
        }
        break;
    }
            String[] str = line.split("\\s+");
String[] str = line.split("\\s+");
private static void search(List<Book> books, Integer bookId) throws BookNotFoundException {
    boolean found = books.stream()
        .anyMatch(t -> {
            System.out.println(t);
            return Objects.equals(t.getBookId(), bookId);
        });

    if (!found) {
        throw new BookNotFoundException("Book ID: " + bookId + " Not Found!");
    }
}