繁体   English   中英

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

[英]Trouble using two Scanners for different input

当使用Scanner从标准输入中读取时,换行符会进入,而原本打算读取的内容不会被占用,从而给后续输入带来麻烦。 可以使用exampleScanner.nextLine() 但是,我尝试使用以下两种不同的扫描仪,但无法解决问题。 我知道在Scanner有很多与此类型的问题有关的问题和答案,但是我似乎仍然找不到我特定问题的答案。 我的问题是否可以解决,或者我必须使用一台Scanner 这是一些代码:

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);
  }
}

错误与此行相关:

scanForSym.close();

在InputStream中关闭System.in。 所以这个电话

x = scanForX.nextInt();

由于scanForX试图从已经关闭的InputStream读取,所以引发IOException。

尝试移动

scanForSym.close();

在某处

x = scanForX.nextInt();

尽管(从注释中重述),但不清楚为什么要在多个Scanner实例都与System.in关联时使用它们。

暂无
暂无

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

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