简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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