Java初学者在这里。为了测试,我制作了自己的使用 BufferedReader 的输入类。代码如下所示:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class inputter {
private static BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
/**
* @param
* A reader for chars
* @throws IOException
*/
public static char getChar() throws IOException{
int buf= read.read();
char chr = (char) buf;
while(!Character.isLetter(chr)){
buf= read.read();
chr = (char) buf;
}
return chr;
}
/**
* @param currencies, names
* A reader for Ints
* @throws IOException
*
*/public static int getInt()throws IOException{
String buf = read.readLine();
while(!buf.matches("[-]?(([1-9][0-9]*)|0)")){
buf = read.readLine();
System.out.print("No valid input. Please try again.");
}
return Integer.parseInt(buf);
}
/**
* @param currencies, names
* A reader for Floats
* @throws IOException
*
*/
public static float getFloat()throws IOException{
String buf = read.readLine();
while(!buf.matches("[-]?(([1-9][0-9]*)|0)(\\.[0-9]+)?")){
System.out.print("No valid input. Please try again.\n");
buf = read.readLine();
}
return java.lang.Float.parseFloat(buf);
}
}
它的问题是,每当我读取一个字符,然后尝试读取一个整数,它就会跳转到 else 条件并输出No valid input. Please try again
。我认为这是因为有旧的输入(例如换行符)到处乱飞。我怎样才能清理它?