在控制台中检测按键 [英] Detect a key press in console

查看:206
本文介绍了在控制台中检测按键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在用户按下某个键时执行某个功能。这将在控制台中运行,代码使用Java。我该怎么做呢?我几乎没有关键按键/键盘的知识,所以我也可以使用一个解释。

I want to execute a certain function when a user presses a key. This will be run in the console, and the code is in Java. How do I do this? I have almost zero knowledge of key presses/keydowns, so I could really use an explanation as well.

推荐答案

如果你想玩控制台,你可以从这开始:

If you want to play with the console, you can start with this:

import java.util.Scanner;

public class ScannerTest {

    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        boolean exit = false;
        while (!exit) {
            System.out.println("Enter command (quit to exit):");
            String input = keyboard.nextLine();
            if(input != null) {
                System.out.println("Your input is : " + input);
                if ("quit".equals(input)) {
                    System.out.println("Exit programm");
                    exit = true;
                } else if ("x".equals(input)) {
                    //Do something
                }
            }
        }
        keyboard.close();
    }
}

只需运行ScannerTest并输入任何文字,然后按

Simply run ScannerTest and type any text, followed by

这篇关于在控制台中检测按键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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