繁体   English   中英

在BufferedReader.read之后,Java抛出NumberFormatException错误

[英]Java throws NumberFormatException error after BufferedReader.read for char

我正在尝试编写一个简单的程序。 我想获得两个用户输入,第一个是char类型,第二个是整数类型。 我正在使用BufferedReader来获取用户输入。 但是当我按下输入后从用户输入char输入后,它会抛出以下错误。

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)

令我惊讶的是,如果我首先获取整数输入然后是char,那么它不会给出任何错误。 但是,如果我首先获取char输入然后是整数,那么它会给出错误。 一旦按下回车键,就会抛出错误。 它甚至没有要求第二次输入。 它将输入视为“”。

这是我的代码。

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的内容到br.readLine()的换行符。 我想你正在输入类似F\\n东西 - 所以br.readLine正在读取F\\n之间的空字符串。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM