java有getchar()方法么

来源:百度知道 编辑:UC知道 时间:2024/09/28 14:40:26
如果没有,怎么实现相当于C语言里的getchar()功能
比如在C里,。你输入abcde然后回车
然后你第一次调用getchar,返回a,第二次调用getchar,返回b。。类似于这样

import java.io.*;

public class Test{

public static void main(String[] args){
char c = '0';
System.out.print("请输入一个字符串:");
for(int i=0; i < 20; i++) {
c = readChar();
if(c != '\n' && c != '\r') {
System.out.println("你刚才输入的字符为:" + c);
}
}
}

//读取字符,但不推荐使用,建议先读取整个字符串,再把字符串转化为字符。
public static char readChar(){
int charAsInt = -1;
try {
charAsInt = System.in.read();
} catch(IOException e) {
System.out.println(e.getMessage());
System.out.println("Fatal error. Ending Program.");
System.exit(0);
}
return (char)charAsInt;
}

}

/*
//推荐这个方法
import java.io.*;

public class Test{
public static void main(String[] args){
try {
System.out.print("请输入一个字符串:");
Buffered