扫描仪nextLine()异常:找不到行 [英] scanner nextLine() exception: no line found

查看:96
本文介绍了扫描仪nextLine()异常:找不到行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为静态方法扫描程序,并发生以下异常:

I'm doing the scanner for a static method, and occur this exception:

Exception in thread "main" java.util.NoSuchElementException: No line found

我的Modify方法趋向于从控制台获得2个字符串作为输入,但是它不起作用. 注意::我没有使用scanner.close();

My modify method tends to get 2 string as input from the console, but it doesn't work. NOTE: I didn't use scanner.close();

static ArrayList<Book> modBook(){
    Book tempbook = Book.searchTitle();

    if(tempbook !=null){
        Scanner sc = new Scanner(System.in);
        int i = BookList.indexOf(tempbook);

        System.out.println("Please enter title:");
        String booktitle = sc.nextLine();
        System.out.println("Please enter author:");
        String bookauthor = sc.nextLine();

        tempbook.setTitle(booktitle);
        tempbook.setAuthor(bookauthor);
        BookList.set(i, tempbook); 

    }
    return BookList;
}

我的搜索方法:

static Book searchTitle(){
    try (Scanner input = new Scanner(System.in)) {
        String booktitle;
        System.out.println("Please enter title:");
        booktitle = input.nextLine();

        for(Book b : BookList){
            if(b.getTitle() != null && b.getTitle().equals(booktitle)){
                System.out.println(b.toString());
                return (Book) b;
            }
        }        
    }catch(Exception e){e.getMessage(); return null;}

    System.out.println("not found");
    return null;
}

推荐答案

您正在静态方法中使用 java.util.Scanner 的两个实例.您只需要使用 java.util.Scanner 的一个实例.删除java.util.Scanner的两个实例,并将其添加为全局变量.

You are using two instance of java.util.Scanner in static methods. You have to used only one instance of java.util.Scanner. Remove the two instances of java.util.Scanner and add this as global variable.

static Scanner input = new Scanner(System.in);

然后使用输入进行代码中的所有读数.完成输入后,请确保关闭输入.

Then used input ONLY to do all the readings in your code. Make sure you close input when you done with it.

这篇关于扫描仪nextLine()异常:找不到行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆