bob
bob

Reputation: 135

Java - Scanner not asking for input, and then crashing

I am trying to get input from the Scanner class, but every time I call it, it crashes the entire program. When trying to catch the exception and print the message, nothing shows up, so I am not even sure what the root of the problem is. Some background info is that this class is being called by the main method, which also has a Scanner that was running, but is closed before this class's method is called.

public class UserHandler {
static Scanner userInput1 = new Scanner(System.in);

static void addInterface() throws IOException, FileNotFoundException{
    boolean addMore = true;
    while(addMore){
        System.out.println("Please enter restaurant name: ");
        String name = userInput1.next();
        if(!FileHandler.containsName(name)){
            System.out.println("Name already exists!");
        }else{
            String[] tags = new String[5];
            System.out.print("\nPlease enter tags seperated by spaces: ");
            for(int i = 0; i < tags.length; i++){
                if(userInput1.hasNext()){
                    tags[i] = userInput1.next();
                }
                else{
                    break;
                }
            }
            FileHandler.addName(name,tags);
        }
    }
}
}

I have tried several times, and was not able to reproduce this issue. I am assuming it is something to do with syntax, or something that is just not called properly. Either way I have spent quite some time trying to fix it, but to no avail.

Upvotes: 0

Views: 449

Answers (1)

piobab
piobab

Reputation: 1352

I suppose that you get the access to the command-line from the first call to the Scanner(System.in), then you close it and when you try to access it the second time you receive IllegalStateException.

Try to use the same instance of the Scanner(System.in) in both situation.

For more info refer to http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html

Upvotes: 1

Related Questions