基于控制台的密钥侦听器 Java

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19028472/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 13:32:24  来源:igfitidea点击:

Console-based Key Listener Java

javaconsolekeyasciilistener

提问by space55

I am trying to write a small text-based game in Java. I had previously written this in C++, but I used "getch()" in C++, and I have no idea what the java equivalent. I am fairly new, and so am not very experienced, but I am able to learn. Is there a Java equivalent to "getch()" in Java? It needs to return the ASCII value of the key. Ideas?

我正在尝试用 Java 编写一个基于文本的小型游戏。我以前用 C++ 写过这个,但我在 C++ 中使用了“getch()”,我不知道 java 等价物是什么。我是新手,所以不是很有经验,但我能够学习。Java中是否有相当于“getch()”的Java?它需要返回密钥的 ASCII 值。想法?

回答by SteveP

In general, you read input from System.in. You can read from this stream in lots of ways, but one option is to use java.util.scanner.

通常,您从 System.in 读取输入。您可以通过多种方式读取此流,但一种选择是使用 java.util.scanner。

Try something like:

尝试类似:

import java.util.Scanner;

Scanner keyboard = new Scanner(System.in);
byte mybyte = keyboard.nextByte();

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html

回答by Talandar

You'll probably want to use

你可能想要使用

InputStreamReader inStream = new InputStreamReader(System.in);
int charValue = inStream.read();

then switch on the character value from there.

然后从那里打开字符值。

As someone else mentioned, Java works on UTF-16, but for characters [a-zA-z0-9] and normal punctuation, you won't notice a difference.

正如其他人提到的,Java 在 UTF-16 上工作,但对于字符 [a-zA-z0-9] 和普通标点符号,您不会注意到区别。

Javadoc for the InputStreamReader: InputStreamReader Javadoc

InputStreamReader 的 JavadocInputStreamReader Javadoc

回答by Ankit Rustagi

You could use a BufferedReaderto replicate getch()

您可以使用BufferedReader来复制 getch()

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class myclass 
{
    public static void main(String[] args) 
    {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Press Enter to continue");
        try 
        {
            int ascii = br.read();
            System.out.println("ASCII Value - "+ascii);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    } 
}

Output

输出

Enter any character to continue
<press a then hit Enter>
ASCII Value - 97