如何捕获回车键,使用扫描仪作为控制台输入? [英] How to capture enter key, using scanner as console input?

查看:22
本文介绍了如何捕获回车键,使用扫描仪作为控制台输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在控制台中捕获输入字符.我正在输入 2 个字符串.

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

案例 1. removestudent(按 Enter)从数组列表中删除所有学生.

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

案例 2. removestudent student1 从数组列表中删除 student1.

Case 2. removestudent student1 removes students1 from array list.

Scanner in=new Scanner();

type_op=in.next();

param=in.next();

if (type_op.equals("removestudent"))
{

    //Calling remove student function and passing param over here.

}

现在案例 2 工作正常.但是,对于案例 1,当用户按下 Enter 键时,我希望参数值为 null.然后我将 param 作为空值传递给我的 remove 函数并删除数组列表中的所有学生.

Now the case 2 works fine. However, for Case 1, I want param value to be null when user presses enter. I will then pass param as a null value to my remove function and delete all the students in the array list.

list1.clear();

请帮助我知道如何获得这个回车键.

Please help me in knowing how to get this enter key.

推荐答案

你可以读取 line,如果 line 是空的,你可以假设它是 enter key.. 就像下面的代码..

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;

这篇关于如何捕获回车键,使用扫描仪作为控制台输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆