方法中的扫描程序对象和NoSuchElementException [英] Scanner objects in methods and NoSuchElementException

查看:102
本文介绍了方法中的扫描程序对象和NoSuchElementException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的试图通过线程找到答案,但仍希望得到一些反馈。

I have really tried to find the answer through the threads but still hope to get some feed back.

下面的代码是糟糕的风格我想但我不知道我知道为什么它在输入数字之后给我开了一个
java.util.NoSuchElementException ,因为我为两种方法制作了两个Scanner对象,我应该能够启动一个新的输入。如果我在inputAndPrintNumber()中删除 input.close(),它可以正常工作和编译。我真的希望知道为什么以及如何修复它如果我仍然使用两个Scanner obj并且如果可能的话没有删除 input.close()

The code below is bad style I think but I don't know why it shoot me a java.util.NoSuchElementException after enter the number since I make two Scanner objects for two methods and I should be able to start a new input. And if I erase the input.close() in inputAndPrintNumber(), it works and compile correctly. I really hope to know why and how to fix it if I still use two Scanner obj and without erasing the input.close() if possible.

import java.util.*;
public class t{

public static void main(String [] args){
    inputAndPrintNumber();
    inputAndPrintString();
}

public static void inputAndPrintNumber(){
    Scanner input = new Scanner(System.in);
    String s = input.nextLine();        
    System.out.print(s);        
    input.close();
}

public static void inputAndPrintString(){
    Scanner input2 = new Scanner(System.in);
    int a = input2.nextInt();       
    System.out.print(a);
}
}

我甚至不确定下面的代码是否是更好还是更好的主意?

I don't even sure whether the code below is better or any better idea?

import java.util.*;

public class t{
public static Scanner input = new Scanner(System.in);
public static void main(String [] args){
    inputAndPrintNumber();
    inputAndPrintString();  
    input.close();
}

public static void inputAndPrintNumber(){
    String s = input.nextLine();        
    System.out.print(s);
}

public static void inputAndPrintString(){
    int a = input.nextInt();        
    System.out.print(a);
}
}


推荐答案

你调用 scanner.close()它不仅会关闭扫描程序,还会从中读取数据,在本例中为 System.in 。因此,如果您要使用 System.in 以后不要关闭它(如果它关闭,我们无法重新打开它并从中读取任何数据,因此例外) 。

When you call scanner.close() it not only closes scanner, but also stream from which it reads data, in this case System.in. So if you are going use System.in later don't close it (if it is closed, we can't reopen it and read any data from it, hence exception).

您的第二个代码示例解决了这个问题,因为当您确定不会从输入流中读取任何其他内容时,Scanner将被关闭。

Your second code example solves this problem because Scanner is being closed when you are sure that nothing else will be read from input stream.

顺便说一下,你似乎混合了 nextLine nextInt nextLine 似乎更适合 inputAndPrintString nextInt for inputAndPrintNumber )。

BTW it seems that you mixed places where nextLine and nextInt should be invoked (nextLine seems to be more appropriate for inputAndPrintString while nextInt for inputAndPrintNumber).

这篇关于方法中的扫描程序对象和NoSuchElementException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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