[英]How to read char from standard input in Java
I have to read char(one at a time) from the standard input in Java.The input will consist of numerous lines (each of about 10000 chars) . 我必须从Java的标准输入中读取char(一次读取一次)。输入将包含许多行(每行约10000个char) 。 I do not need to store the chars , they are processed when read.Also I need to skip the newline char .Can someone suggest me an efficient way to do this ?
我不需要存储字符,它们在读取时会被处理。我还需要跳过换行符char。有人可以建议我这样做的有效方法吗?
I guess you need something like this. 我猜你需要这样的东西。 Replace the # with whatever appropriate.
将#替换为适当的值。
import java.io.InputStreamReader;
public class Test022 {
public static void main(String[] args) throws Exception {
InputStreamReader br = new InputStreamReader(System.in);
char ch = ' ';
while (true){
ch = (char)br.read();
if (ch == '#') break;
else if (ch == '\n') continue;
else if (ch == '\r') continue;
System.out.println("Char read: " + ch);
}
}
}
Perhaps something like this will work: 也许这样的事情会起作用:
import java.io.IOException;
public class Tester
{
public static void main(String args[])
throws IOException
{
int ch;
while ((ch = System.in.read()) != -1)
{
if (ch != '\n' && ch != '\r')
{
processChar((char)ch);
}
}
}
private static void processChar(char c)
{
// do stuff
System.out.println("Processing: '" + c + "'");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.