[英]How to read char from standard input in Java
我必須從Java的標准輸入中讀取char(一次讀取一次)。輸入將包含許多行(每行約10000個char) 。 我不需要存儲字符,它們在讀取時會被處理。我還需要跳過換行符char。有人可以建議我這樣做的有效方法嗎?
我猜你需要這樣的東西。 將#替換為適當的值。
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);
}
}
}
也許這樣的事情會起作用:
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.