[英]Java throws NumberFormatException error after BufferedReader.read for char
I am trying to write a simple program. 我正在尝试编写一个简单的程序。 I am trying to get two user input, first one is of type char and second one is of type integer.
我想获得两个用户输入,第一个是char类型,第二个是整数类型。 I am using BufferedReader for taking user input.
我正在使用BufferedReader来获取用户输入。 However after taking char input from user when I am pressing enter it is throwing below error.
但是当我按下输入后从用户输入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)
To my surprise if I am taking integer input first and then char then it is not giving any error. 令我惊讶的是,如果我首先获取整数输入然后是char,那么它不会给出任何错误。 however if I am taking char input first and then integer then it is giving error.
但是,如果我首先获取char输入然后是整数,那么它会给出错误。 As soon as I am pressing enter key it is throwing error.
一旦按下回车键,就会抛出错误。 It is not even asking for second input.
它甚至没有要求第二次输入。 It is considering the input as "".
它将输入视为“”。
Here is my code. 这是我的代码。
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);
}
}
You should use br.readLine()
to get the sex, and use String.charAt(0)
to get the first character of it (with appropriate checking, of course): 您应该使用
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);
}
}
Currently, your call to br.readLine()
is reading the contents of System.in
from immediately after the single-character sex up to the newline following it. 目前,您对
br.readLine()
调用是从单字符性别之后立即读取System.in
的内容到br.readLine()
的换行符。 I guess you are entering something like F\\n
- so br.readLine
is reading the empty string between F
and the \\n
exclusively. 我想你正在输入类似
F\\n
东西 - 所以br.readLine
正在读取F
和\\n
之间的空字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.