我正在尝试编写一个java程序来逐个字符地处理连续类型。 基本上,这意味着有一个字符串变量“input”来记录当前输入的字符串。 因此,如果当前类型为“W”,则输入应为“W”,并且用户保持类型为“h”,则输入应为“Wh”,依此类推。
我希望它是一个字符一个字符,我认为它应该是使用扫描仪的一些 while 循环?
好的。我可以一串一串地做。但扫描仪什么时候停止? 我尝试过:
while(in.hasNext()){ 字符串 temp = in.next(); if(temp.equals("")){ 休息; } }
但是扫描仪并没有停止。循环没有停止。 java的输入值是多少 从“输入返回”键?我需要导入键盘监听器吗?
最佳答案
不,扫描仪将无法工作,因为它仅在按下 ENTER
后接受字符串。您将需要一个非标准控制台或创建一个 Swing GUI,使用添加了 DocumentListener 的 JTextField。
编辑
对于@tieTYT
他给出了一个链接this answer建议使用Console来解决这个问题。将他的代码放入一个小程序中:
import java.io.Console;
import java.io.IOException;
public class Test {
public static void main(String[] args) throws IOException {
Console cons = System.console();
if (cons == null) {
System.out.println("Console is null");
System.exit(-1);
} else {
System.out.println("Enter text, or \"z\" to exit:");
while (true) {
char c = (char) cons.reader().read();
System.out.println("" + c);
if (c == 'z') {
System.exit(0);
}
}
}
}
}
关于java - 如何编写java程序来处理连续的字符输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22797389/