java每次读取控制台上按下的每个键 [英] java read every key pressed on console at a time

查看:474
本文介绍了java每次读取控制台上按下的每个键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

第一次提出问题。



我想要的是每当用户按下控制台上的某个键时发生的一些操作。喜欢,当他键入一个单词,我想要在每个按键,一个字符串形成的所有已经按下的键,打印,连接到新按下的键。如:



a



您键入:a



b



您输入的是:ab



c



您键入的是:abc



d



您键入的是:abcd



e



您输入的是:abcde



使用以下代码:

  try(BufferedReader input = new BufferedReader(
new InputStreamReader(System.in,UTF -8))){
char c = 0;
String s =;
while((c =(char)input.read())!= 13){
s + = c;
System.out.println(You typed:+ s);
}
}

我得到了我想要的,



您键入的是:f

p>

您键入:fo



您键入:foo



您键入的内容:foob



您键入的内容:fooba



您键入:foobar



提前感谢。

解决方案

看起来其他人问过这个问题。它也似乎是一致的是,修改System.in是不同的平台,为了做你想要的,你将需要将终端从线模式更改为字符模式。



查看此处


first time making a question.

What I want is a way of every time the user presses a key on the console certains actions take place. Like, as he types a word, I want at every keypress for a String formed by all the keys he's already pressed to be printed, concatenated to the newly pressed key. As in:

a

You typed: a

b

You typed: ab

c

You typed: abc

d

You typed: abcd

e

You typed: abcde

I'm trying to do this with the following code:

try (BufferedReader input = new BufferedReader(
                            new InputStreamReader(System.in, "UTF-8"))) {
    char c = 0;
    String s = "";
    while( (c = (char) input.read() ) != 13) {
        s += c;
        System.out.println("You typed: " + s);
    }
}

I get what I want, but just after I press the Enter key, not as every key pressed on the console:

foobar

You typed: f

You typed: fo

You typed: foo

You typed: foob

You typed: fooba

You typed: foobar

Thanks in advance.

解决方案

It looks like someone else has asked this question. It also looks like that consensus is that modifying System.in is different across platforms and in order to do what you want, you would need to change the terminal from "line" mode to "character" mode.

Take a look Here.

这篇关于java每次读取控制台上按下的每个键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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