【问题标题】:Java throws NumberFormatException error after BufferedReader.read for charJava 在 BufferedReader.read for char 之后抛出 NumberFormatException 错误
【发布时间】:2016-02-03 08:32:47
【问题描述】:

我正在尝试编写一个简单的程序。我正在尝试获取两个用户输入,第一个是 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);            
}
}

【问题讨论】:

  • 请注意,InputStream.read() 返回的是 byte,而不是 char。如果你想要一个char,你应该把它包裹在一个InputStreamReader中。
  • NumberFormatException:对于输入字符串:“”是一条足够清晰的消息。你有什么不明白的。

标签: java bufferedreader


【解决方案1】:

您应该使用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 之间的空字符串。

【讨论】:

  • 我正在输入性别值“M”并按回车键。我没有输入 \n 等。但是,一旦我按下输入键,它就会抛出错误。它将 empcode 的输入作为“”。
  • 你认为回车键是什么字符?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-29
  • 2020-06-12
  • 1970-01-01
  • 1970-01-01
  • 2022-07-14
  • 1970-01-01
相关资源
最近更新 更多