How can I repeatedly read user input using Scanner java

前端 未结 3 1034
一个人的身影
一个人的身影 2021-01-24 13:08

I am trying to create a simple menu for my program that reads user input. Here\'s the code:

public void menu() {
        String command;

        System.out.prin         


        
相关标签:
3条回答
  • 2021-01-24 13:16

    You can use

    InputStreamReader str= new InputStreamReader (System.in);
    BufferedReader uinp= new BufferedReader (str);
    String val;
    val= uinp.readLine();
    while (!".".equals(val)) {
    //do your stuff
    //..and after done, read the next line of the user input.
    val= uinp.readLine();
    }
    
    0 讨论(0)
  • 2021-01-24 13:24

    Why not do something like this:

    public class test {
    
    private static Scanner scanner;
    
    public static void main(String args[]) {
        scanner = new Scanner(System.in);
        printmenu();      
        getinput();
    }
    
    private static void printmenu(){
        System.out.println("To operate with words write: a");
        System.out.println("To operate with products write: b");
    }
    
    private static void getinput(){
        System.out.print("\nGive the command: ");
        String command = "";
        while (!scanner.hasNext()) {
    
        }
        command = scanner.next();
    
        if (command.equals("a")) {
            System.out.println("\nGood job! You have chosen the word program\n");
            System.out.println("You can only use the following commands: ");
            System.out.println("exit - to exit the program");
            System.out.println("add - to add a word into the map");
            System.out.println("lookup - to lookup a word into the map\n");
            System.out.print("Give a command: ");
    
            while(scanner.hasNext()){
                command = scanner.next();
                if(command.contains("add")){
    
                    addWord();
                }
                else{
                    System.out.println(command);
                }
                getinput();
            }
        }
        else{
            scanner.close();
        }
    }
    
    public static void addWord() {
    
        System.out.print("Give the word: ");
        String word = scanner.next();
        System.out.print("Give the word's plural: ");
        String plural = scanner.next();
        //controller.addTheWord(word, plural);
    }
    

    }

    0 讨论(0)
  • 2021-01-24 13:37

    You should use switch case inside the while loop instead of if. The switch case should provide the functionality depending on the input provided by the user.

    0 讨论(0)
提交回复
热议问题