java程序如何从键盘中读入单个字符
java程序如何从键盘中读入单个字符不是字符串
求助 --------------------编程问答--------------------
--------------------编程问答-------------------- 猜测你是要监听键盘事件,不知道是不是
Scanner in = new Scanner(System.in);
//读一行
String s1 = in.nextLine();
//读string
String s = in.next();
// int
int i =in.nextInt();
--------------------编程问答-------------------- 我想通过输入的字符判断是不是空格退出输入循环,3楼朋友幸苦了,谢谢 --------------------编程问答-------------------- 可以啊,你判断监听的点击返回的是不是空格或者你想要的那个按键就可以了啊 --------------------编程问答--------------------
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowAdapter;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
class MyKeyHandle extends JFrame implements KeyListener {
private JTextArea text = new JTextArea();
public MyKeyHandle() {
super.setTitle("Welcome!");
JScrollPane scr = new JScrollPane(text);
scr.setBounds(5, 5, 300, 200);
super.add(scr);
text.addKeyListener(this);
super.setSize(310, 210);
super.setVisible(true);
super.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent arg0) {
System.exit(1);
}
});
}
@Override
public void keyTyped(KeyEvent e) {
text.append("输入的内容是:" + e.getKeyChar() + "\n");
}
@Override
public void keyPressed(KeyEvent e) {
text.append("键盘“" + KeyEvent.getKeyText(e.getKeyCode()) + "”键按下\n");
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
text.append("键盘“" + KeyEvent.getKeyText(e.getKeyCode()) + "”键松开\n");
}
public static void main(String[] args) {
new MyKeyHandle();
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class OneKey {
public static void main(String[] args){
char k='a';
try {
/**
* 循环判断其是否为空格,不是继续读
*/
while(!Character.isWhitespace(k)){
System.out.println("请输入空格");
BufferedReader br1=new BufferedReader(new InputStreamReader(System.in));
k = (char) br1.read();
}
System.out.println("空格退出");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
见代码,System.out.println("请输入空格");为当输入不是空格时的处理
补充:Java , Java SE