3
I have declared two strings and reading the input using Scanner(System.in).

この後、スキャナーを閉じて、スキャナーを使用して別の入力を再度読み取ると、エラーがスローされます: NoSuchElementException。これについて私を案内してください

import java.util.Scanner;
import java.io.*;  

public class NumericInput

{
  public static void main(String[] args)
  {
    // Declarations
    Scanner in = new Scanner(System.in);
    String string1;
    String string2;

   // Prompts 
    System.out.println("Enter the value of the First String .");
   // Read in values  
    string1 = in.nextLine();
    // When i am commenting below line(in.close) code is working properly. 
    in.close();
    Scanner sc = new Scanner(System.in);
    System.out.println("Now enter another value.");
    string2 = sc.next();
    sc.close();

    System.out.println("Here is what you entered: ");
    System.out.println(string1 + " and " + string2);
  }

}
4

2 に答える 2

0

Scanner を閉じる必要はありません。これはAutoCloseableインターフェースを実装しているため、Java 7 以降の try-with-resources でリソースを宣言する必要があります。 Scanner を閉じることが問題になる場合。

try(Scanner in = new Scanner(System.in); Scanner sc = new Scanner(System.in)){
 // do stuff here without closing
}

 catch(Exception){
  e.printStackTrace();
 }
于 2014-12-30T08:13:19.953 に答える