为什么我得到inputmismatchexception?

时间:2014-05-04 01:39:05

标签: java

我只是想让它在txt文件中打印信息,但我一直在努力 这个问题和idk如何解决它。我注释掉了inFile,我只是指出了所以我可以用文字填充这个,所以我可以发布这个。

import java.util.*;
import java.io.*;
public class P175ex6 {
static Scanner console=new Scanner(System.in);
public static void main (String[] args)
throws FileNotFoundException{
    //Scanner inFile=new Scanner(new FileReader("prog.dat"));
    PrintWriter outFile=new PrintWriter("prog.txt");
    double gross,fedtax,statetax,sstax,medcare_caidtax,pensionplan,healthinsur,netpay;
    String name;
    System.out.println("Please input employee name");
    name=console.next();
    System.out.println("Please input employee gross pay");
    gross=console.nextDouble();

我在收到总薪水时收到此错误消息?

Please input employee name
Bill Robinson
Please input employee gross amount
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextDouble(Unknown Source)
at P175ex6.main(P175ex6.java:14)

2 个答案:

答案 0 :(得分:1)

我们可以看到异常被抛出这一行:

gross = console.nextDouble();

所以无论你输入什么都不是一个合适的双倍。

编辑:

之前的回答不正确。这实际上是因为这一行:

console.next();

这只会读取下一个标记,即“Bill”,这会导致console.nextDouble()读取“Robinson”导致错误。

要解决此问题,请将console.next()替换为console.nextLine()

答案 1 :(得分:0)

错误很明显。它希望员工工资增加一倍,而且你输了一个字符串。

我修改了你的代码并在eclipse中尝试了它并且没有错误 -

package foo;
import java.util.*;
import java.io.*;
public class P175ex6 {
static Scanner console=new Scanner(System.in);
public static void main (String[] args)
throws FileNotFoundException{
    double gross;
    String name;
    System.out.println("Please input employee name");
    name=console.next();
    System.out.println("Please input employee gross pay");
    gross=console.nextDouble();
    }
}

控制台 -

Please input employee name
bing
Please input employee gross pay
111