1

I have really tried to find the answer through the threads but still hope to get some feed back.

The code below is bad style I think but I don't know why it shoot me a java.util.NoSuchElementException after enter the number since I make two Scanner objects for two methods and I should be able to start a new input. And if I erase the input.close() in inputAndPrintNumber(), it works and compile correctly. I really hope to know why and how to fix it if I still use two Scanner obj and without erasing the input.close() if possible.

import java.util.*;
public class t{

public static void main(String [] args){
    inputAndPrintNumber();
    inputAndPrintString();
}

public static void inputAndPrintNumber(){
    Scanner input = new Scanner(System.in);
    String s = input.nextLine();        
    System.out.print(s);        
    input.close();
}

public static void inputAndPrintString(){
    Scanner input2 = new Scanner(System.in);
    int a = input2.nextInt();       
    System.out.print(a);
}
}

I don't even sure whether the code below is better or any better idea?

import java.util.*;

public class t{
public static Scanner input = new Scanner(System.in);
public static void main(String [] args){
    inputAndPrintNumber();
    inputAndPrintString();  
    input.close();
}

public static void inputAndPrintNumber(){
    String s = input.nextLine();        
    System.out.print(s);
}

public static void inputAndPrintString(){
    int a = input.nextInt();        
    System.out.print(a);
}
}
JasonMArcher
  • 14,195
  • 22
  • 56
  • 52

1 Answers1

2

When you call scanner.close() it not only closes scanner, but also stream from which it reads data, in this case System.in. So if you are going use System.in later don't close it (if it is closed, we can't reopen it and read any data from it, hence exception).

Your second code example solves this problem because Scanner is being closed when you are sure that nothing else will be read from input stream.

BTW it seems that you mixed places where nextLine and nextInt should be invoked (nextLine seems to be more appropriate for inputAndPrintString while nextInt for inputAndPrintNumber).

Pshemo
  • 122,468
  • 25
  • 185
  • 269
  • Thank you Pshemo, I choose to send Scanner object to any methods needs inputs. Just still wondering the best way to do this task. – Wei-Cheng David Dec 14 '14 at 18:49
  • It is hard to tell which way is the best because it all depends on how you want to use your scanner. Main point is to not recreate scanner each time you want to read data from user and not to close it if you are going to read more data. If you decide to create scanner in main method and pass it to other methods it is OK. It would also be OK to use your second approach but just change accessibility to `public static Scanner input = new Scanner(System.in);` because this way you also are creating one scanner and reusing it in your methods. – Pshemo Dec 14 '14 at 19:07