How to capture enter key, using scanner as console input?

前端 未结 2 1559
挽巷
挽巷 2020-12-12 03:44

I want to capture enter character in console. I am inputting 2 strings.

Case 1. removestudent(pressing enter) removes all the students from array list.

Cas

相关标签:
2条回答
  • 2020-12-12 04:03

    I think this will help you

    Scanner input= new Scanner(System.in);
    String readString = input.nextLine();
    while(readString!=null) {
        System.out.println(readString);
        if (readString.equals(""))
            System.out.println("Read Enter Key.");
        if (input.hasNextLine())
            readString = input.nextLine();
        else
            readString = null;
    }
    
    0 讨论(0)
  • 2020-12-12 04:18

    You can read line and if line is blank, You can assume it is enter key.. like below code..

    Scanner scanner = new Scanner(System.in);
    String readString = scanner.nextLine();
    System.out.println(readString);
    if (readString.equals(""))
        System.out.println("Enter Key pressed.");
    if (scanner.hasNextLine())
        readString = scanner.nextLine();
    else
        readString = null;
    
    0 讨论(0)
提交回复
热议问题