在这个程序中,每次运行程序时都会跳过行char g = (char)(br.read())
。输入年龄后,如果我输入性别为m,我收到错误java.lang.NumberFormatException。
import java.io.*;
public class Tax
{
public static void main()throws IOException
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
System.out.println("Enter age");
int age = Integer.parseInt(br.readLine());
System.out.println("Enter gender as m or f");
char g = (char)(br.read());
System.out.println("Enter Taxable Income");
int ti = Integer.parseInt(br.readLine());
double in;
if (age > 65 || g == 'f')
System.out.println("Wrong Category");
else
{
if (ti <= 160000)
in = 0;
else if(ti > 160000 && ti<=500000)
in = (ti - 160000) * (10.0/100.0);
else if(ti > 500000 && ti<=800000)
in = (ti - 50000) * (20.0/100.0) + 34000;
else
in = (ti - 800000) * (30.0/100.0) + 94000;
System.out.println("Income Tax = " + in);
}
}
}
但如果程序修改如下,即。如果char g = (char)(br.read());
被String g = br.readLine()
替换,则可以使用
import java.io.*;
public class Tax
{
public static void main()throws IOException
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
System.out.println("Enter age");
int age = Integer.parseInt(br.readLine());
System.out.println("Enter gender as m or f");
String g = br.readLine();
System.out.println("Enter Taxable Income");
int ti = Integer.parseInt(br.readLine());
double in;
if (age > 65 || g.equalsIgnoreCase("f"))
System.out.println("Wrong Category");
else
{
if (ti <= 160000)
in = 0;
else if(ti > 160000 && ti<=500000)
in = (ti - 160000) * (10.0/100.0);
else if(ti > 500000 && ti<=800000)
in = (ti - 50000) * (20.0/100.0) + 34000;
else
in = (ti - 800000) * (30.0/100.0) + 94000;
System.out.println("Income Tax = " + in);
}
}
}
答案 0 :(得分:6)
问题是你只是从阅读器中读取一个字符 - 让行分隔符部分仍然可以读取。
因此,如果BufferedReader
逻辑上包含:
30\r\nm\r\n20
然后:
readLine()
将消耗"30\r\n"
。read()
将消耗"m"
离开\r\n20
readLine()
将消耗"\r\n"
,返回空字符串如果你真的输入“30”,点击返回,然后输入“m20”并点击返回,它会起作用 - 但显然这不是你想要的:)
使用扫描仪,或只使用readLine()
并检查“m”和“f”的行内容。
答案 1 :(得分:2)
尝试使用扫描仪,如
char g;
Scanner scan = new Scanner (System.in);
g = scan.nextChar();`
答案 2 :(得分:0)
你只读一个字节,这意味着你写的是
m 22
这个menas你在数字之前有一个空格,如果你输入
m
22
这意味着m
之后的其余部分为空白。
这就是我写它的方式
Scanner in = new Scanner(System.in);
System.out.println("Enter age");
int age = in.nextInt(); in.nextLine();
System.out.println("Enter gender as m or f");
String mf = in.next(); in.nextLine();
System.out.println("Enter Taxable Income");
int ti = in.nextInt(); in.nextLine();