Java在BufferedReader.read for char后引发NumberFormatException错误

Java在BufferedReader.read for char后引发NumberFormatException错误,java,bufferedreader,Java,Bufferedreader,我想写一个简单的程序。我试图获得两个用户输入,第一个是char类型,第二个是integer类型。我使用BufferedReader获取用户输入。然而,当我按enter键从用户获取字符输入后,它抛出了下面的错误 Please enter your sex: m Please enter your code: Please enter your salary: Exception in thread "main" jav a.lang.NumberFormatException: For input

我想写一个简单的程序。我试图获得两个用户输入,第一个是char类型,第二个是integer类型。我使用BufferedReader获取用户输入。然而,当我按enter键从用户获取字符输入后,它抛出了下面的错误

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)
获取性别的第一个字符(当然要进行适当的检查):


当前,您对
br.readLine()
的调用正在读取
System.in
的内容,从紧跟在单字符sex之后一直到其后的换行符。我猜您输入的是类似于
F\n
-因此
br.readLine
以独占方式读取
F
\n
之间的空字符串。

注意
InputStream.read()
返回的是
字节,而不是
char
。如果需要
字符
,则应将其包装在
InputStreamReader
中。NumberFormatException:For input string:“”是一条足够清晰的消息。你们有什么不明白的。我正在输入一个值“M”表示性,然后按回车键。我没有输入\n等。但是,只要我按enter键,就会抛出错误。它将empcode的输入作为“”。您认为enter键类型是什么字符?
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);
  }
}