从扫描仪传递值时出现异常

时间:2014-11-19 23:05:52

标签: java java.util.scanner

我在“talis probability”中尝试使用键盘第二扫描仪输入类型时出现异常。主要是我试图改变键盘的尾部概率..

 Number of threads: 2
Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:862)
    at java.util.Scanner.next(Scanner.java:1485)
    at java.util.Scanner.nextFloat(Scanner.java:2345)
    at rzutmoneta.Toss.main(Toss.java:32)
talis probability: Java Result: 1

并且不知道为什么......但我知道这个问题可能在这里“最后一班硬币”..如何修复我的程序?

final class Toss {
 public static float p;

  public static void main(String... argv) {


    System.out.print("Number of threads: ");
    int how_much;
    try (Scanner input = new Scanner(System.in)) {
      how_much = input.nextInt();
    }

    System.out.print("talis probability: ");

    try (Scanner input = new Scanner(System.in)) {
      p = input.nextFloat();
    }

    ExecutorService threads = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    for (int i = 0; i < how_much; ++i)
      threads.submit(Toss::run);
    threads.shutdown();
  }

  private static void run() {
    Coin coin = new Coin();
    int count = 0;
    while (coin.flip() == Coin.UpDown.Tails) {
      System.out.println(Thread.currentThread().getName() + ": Talis!");
      ++count;
    }
    System.out.printf("%s: heads! %d talis%n", Thread.currentThread().getName(), count);
  }

}

final class  Coin {
   public static float p;

    Coin() {
         Toss.p = Coin.p;
    }

  enum UpDown {
    Heads, Tails
   }

  UpDown flip() {

    //return ThreadLocalRandom.current().nextBoolean() ? Strony.Orzeł : Strony.Reszka;
    return ThreadLocalRandom.current().nextFloat() < p ? UpDown.Heads : UpDown.Tails;  
  }

}

1 个答案:

答案 0 :(得分:1)

使用此代码:

try (Scanner input = new Scanner(System.in)) {
  how_much = input.nextInt();
}

您正在使用Java的try-with-resources语法的自动关闭功能。扫描程序会调用close()来关闭基础System.in,因此下次System.in创建新的扫描程序不起作用,因为System.in已关闭。

而是创建一个扫描程序,并在命令行上与用户进行每次交互时使用它。