在Java内部类中使用Scanner而不引发异常的方法是否存在?

huangapple go评论57阅读模式
英文:

Is there a way to use Scanners in an inner class inside of Java without an exception

问题

我有一个顶级公共类,其中包含一个内部类,该内部类通过创建顶级类的实例,然后在该顶级类的实例中创建内部类的实例来创建。

我遇到的问题是,在我创建Scanner对象并尝试运行next()方法之后,程序不允许终端输入任何内容,然后抛出一个错误,因为没有标记可供其捕获。

我尝试过使用hasNext()方法和使用try-catch。对我来说,预期的行为是Scanner对象使线程等待终端输入。

以下是我的代码:

import java.util.Scanner;

public class ScannerTest {
    public static void main(String args[]){
        Scanner input  = new Scanner(System.in);
        System.out.print("输入一个数字: ");
        int inputValue = input.nextInt();
        input.close();
        System.out.printf("%d 乘以 5 等于 %d%n%n", inputValue, inputValue*5);

        ScannerTest m = new ScannerTest();
        Scanner2 g = m.new Scanner2();
        g.gG();
    }

    private class Scanner2{

        public void gG(){

            Scanner in = new Scanner(System.in);

            System.out.println("请输入一个单词: ");

            String firstWord = in.next();
            in.close();

            System.out.println("第一个单词: " + firstWord); 
        }
    }
}

异常 - Exception in thread "main" java.util.NoSuchElementException: No line found - 发生在达到String firstWord = in.next();时。再次强调,这段代码通常不会很有用,但我正在尝试实验可能性。

英文:

I have a Top-level public class with an inner class being created in that same class by creating an instance of the top-level class and then creating an instance of the inner class in that instance of the top-level class.

The issue I'm running into is that after I create the Scanner object and try to run the next() method, is that the program doesn't allow for the terminal to input anything and then throws an error for there not being a token for it to pick up on.

I have tried using the hasNext() method and using try_catch. For me, the intended behavior is that the Scanner object makes the Thread wait for an input from the terminal.

Here is my code:

import java.util.Scanner;

public class ScannerTest {
    public static void main(String args[]){
        Scanner input  = new Scanner(System.in);
        System.out.print("ENTER A NUMBER: ");
        int inputValue = input.nextInt();
        input.close();
        System.out.printf("%d multiplied by 5 is equal to %d%n%n", inputValue, inputValue*5);

        ScannerTest m = new ScannerTest();
        Scanner2 g = m.new Scanner2();
        g.gG();
    }

    private class Scanner2{

        public void gG(){

            Scanner in = new Scanner(System.in);

            System.out.println("Please enter a word: ");

            String firstWord = in.next();
            in.close();

            System.out.println("First word: " + firstWord); 
        }
    }
}

The exception - Exception in thread "main" java.util.NoSuchElementException: No line found - happens when String firstWord = in.next(); is reached. Again, this code is obviously not going to be very useful normally, but I'm trying to experiment with what's possible.

答案1

得分: 0

当您调用Scanner.close()时,就像在您的代码中这样:

input.close();

Scanner也会关闭其正在读取的底层流。在您的情况下,这会关闭System.in。因此,当您试图在g.gG()中再次使用ScannerSystem.in读取时,因为流已经关闭,所以没有内容可读。这就是您遇到此异常的原因。

正确的行为应该是在使用完System.in后关闭它,即在程序结束时。然而,由于运行时会在程序退出时自动关闭它,所以没有必要这样做。

附注:另外,如果您确实想要或需要关闭某些东西,通常应该使用try..finallytry-with-resources语句来确保在发生异常时不会跳过该语句,这可能会导致内存或资源泄漏。

英文:

When you call Scanner.close(), as in your line

input.close();

the Scanner will also close the underlying stream from which it is reading. In your case this closes System.in. So when you are trying to use a Scanner in g.gG() to read from System.in again there is nothing to read because the stream has already been closed. This is why you are getting this exception.

The correct behaviour would be to close System.in when you are done using it, i.e. at the end of the program. However, there is no need to do that since the runtime will close it automatically when the program exits.

PS: on a separate note, if you do want or need to close something you should normally use a try..finally or try-with-resources statement to ensure that the statement is not skipped in the case of exception which could lead to memory or resource leaks.

huangapple
  • 本文由 发表于 2023年7月3日 14:09:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/76602205.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定