简体   繁体   English

使用两个扫描仪输入不同的故障

[英]Trouble using two Scanners for different input

When using Scanner to read from standard input, the newline one enters apart from what's intended to be read is not consumed, causing trouble with subsequent inputs. 当使用Scanner从标准输入中读取时,换行符会进入,而原本打算读取的内容不会被占用,从而给后续输入带来麻烦。 This can be fixed using something like exampleScanner.nextLine() . 可以使用exampleScanner.nextLine() However I'm trying to use two different scanners as below and am not able to fix the problem. 但是,我尝试使用以下两种不同的扫描仪,但无法解决问题。 I know there are a ton of questions and answers related to this type of problem with Scanner but I still can't seem to find an answer to my particular problem. 我知道在Scanner有很多与此类型的问题有关的问题和答案,但是我似乎仍然找不到我特定问题的答案。 Is my problem fixable or do I have to make do with one Scanner ? 我的问题是否可以解决,或者我必须使用一台Scanner Here's some code: 这是一些代码:

import java.util.Scanner;
import java.util.NoSuchElementException;

public class ScannerTest {
  public static void main(String[] args) {

    char sym = ' ';
    int x = 0;

    /* scan for char (string) */
    Scanner scanForSym = new Scanner(System.in);
    System.out.print("Enter a symbol: ");
    try {
      sym = scanForSym.next().charAt(0);
    } catch (NoSuchElementException e) {
      System.err.println("Failed to read sym: "+e.getMessage());
    }
    scanForSym.nextLine(); // makes no diff when using different Scanner
    scanForSym.close();

    /* scan for int with different scanner */
    Scanner scanForX = new Scanner(System.in);
    System.out.print("\nEnter an integer: ");
    try {
      x = scanForX.nextInt();
      //x = scanForSym.next(); // this works fine (comment out the close above)
    } catch (NoSuchElementException e) {
      System.err.println("Failed to read x: "+e.getMessage());
    }
    scanForX.close();

    System.out.println("sym: "+sym);
    System.out.println("x: "+x);
  }
}

Error is associated with this line: 错误与此行相关:

scanForSym.close();

which closes the System.in InputStream. 在InputStream中关闭System.in。 So then this call 所以这个电话

x = scanForX.nextInt();

throws an IOException since scanForX is trying to read from an already closed InputStream. 由于scanForX试图从已经关闭的InputStream读取,所以引发IOException。

Try moving 尝试移动

scanForSym.close();

somewhere below 在某处

x = scanForX.nextInt();

Although (restating from the comments) it's not clear why you want to use multiple Scanner instances when they're both associated with System.in . 尽管(从注释中重述),但不清楚为什么要在多个Scanner实例都与System.in关联时使用它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM