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);
}
}
它的问题是,例如,每当我读取一个char并尝试读取一个整数之后,它就会跳转到else条件并输出
No valid input. Please try again
。我认为这是因为有旧的输入内容(例如换行符)飞来飞去。我该如何清理? 最佳答案
看来问题出在您的输入序列上:
尝试输入以下序列:“ a1 [enter]”。您的代码应适用于这种输入。但是,如果输入“ a [enter] 1 [enter]”,则代码将失败。
原因是[enter]键仅在执行下一个readline()时才处理,并且它与数字格式不匹配,因此进入else条件。