我正在尝试编写一个简单的程序。我正在尝试获取两个用户输入,第一个是 char 类型,第二个是整数类型。我正在使用 BufferedReader 获取用户输入。但是,当我按下回车键时从用户那里获取字符输入后,它会抛出以下错误。
Please enter your sex: m
Please enter your code: Please enter your salary: Exception in thread "main" jav
a.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at classtest.main(classtest.java:24)
令我惊讶的是,如果我先输入整数然后输入字符,那么它不会给出任何错误。但是,如果我先输入字符,然后再输入整数,则会出现错误。只要我按下回车键,它就会抛出错误。它甚至不要求第二次输入。它将输入视为“”。
这是我的代码。
import java.io.*;
import java.util.*;
public class classtest
{
public static void main(String[] args) throws IOException
{
BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
int empcode;
char sex;
System.out.print("Please enter your sex: ");
sex=(char)System.in.read();
System.out.print("Please enter your code: ");
empcode=Integer.parseInt(br.readLine());
System.out.print("Code: " +empcode);
System.out.print("Sex: " + sex);
}
}
最佳答案
您应该使用 br.readLine()
获取性别,并使用 String.charAt(0)
获取它的第一个字符(通过适当的检查,当然):
sex = '?';
while (sex != 'M' && sex != 'F') {
System.out.print("Please enter your sex: ");
String line = br.readLine();
if (line.length() == 1) {
sex = line.charAt(0);
}
}
目前,您对 br.readLine()
的调用正在读取 System.in
的内容,从单字符性别之后到它后面的换行符。我猜你正在输入类似 F\n
的内容 - 所以 br.readLine
正在读取 F
和 \n 之间的空字符串
独家。
关于Java 在 BufferedReader.read for char 之后抛出 NumberFormatException 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35171991/