2016-03-26 84 views
-1

我有我的try/catch语句的问题。我知道这可能是一个简单的解决方案,但我是新来的Java。 在这里,我想要控制台提示用户添加他们的初始存款,例如,如果我输入像“你好”的程序会崩溃,而不是再次询问?感谢尝试和赶不工作

这里是我收到的错误: 异常线程 “main” java.util.InputMismatchException 在

java.util.Scanner.throwFor(来源不明)

在java中。 util.Scanner.next(未知来源)

在java.util.Scanner.nextInt(未知来源)

在java.util.Scanner.nextInt(未知来源)

System.out.println("Please enter an initial deposit:"); 
      try{ 

       deposit.add(keyboard.nextInt()); 

      }catch(NumberFormatException e){ 

       System.out.println("Invalid input"); 

      System.out.println("Please enter an account number:"); 
      accountNumber.add(keyboard.nextDouble()); 
+3

缺少一个右括号的? catch(NumberFormatException e){System.out.println(“Invalid input”);} /*...*/ System.out.println(“请输入帐号:”); ' –

+0

您是否收到任何错误?如果是,他们是什么? –

+0

你有没有检查你得到了什么异常?例如,如果你在线程“main”java.util.InputMismatchException中得到异常,那么你不能捕获使用NumberFormatException? – Suparna

回答

2
根据 docs

方法nextInt

抛出InputMismatchException时没有NumberFormatException的

写:

catch(InputMismatchException e){ 
     .... 

更新: 我用这个片段,并输入查询作品数量

public static void main(String[] args) { 

    Scanner keyboard = new Scanner(System.in); 

    System.out.println("Please enter an initial deposit:"); 

    try { 
     int numberEntered = keyboard.nextInt(); 
     System.out.println(numberEntered); 

    } catch (InputMismatchException e) { 

     System.out.println("Invalid input"); 

     System.out.println("Please enter an account number:"); 
    } finally { 
     keyboard.close(); 
    } 
} 

控制台:

Please enter an initial deposit: 
55 
55 

Process finished with exit code 0 
+0

这可以稍微改善一点。它实际上显示“无效输入” 然而,继续“请输入一个帐号”,然后崩溃与'线程异常' –

+0

我扩展了答案,希望它可以帮助你调试你的代码 – tjago

1
  1. 你没有得到你捕捉到的异常。相反,你得到InputMismatchException。

  2. 由于您试图在catch语句中再次输入输入,您必须再次输入无效输入。但是,谁抓住了这个例外?没有人。因此,你的程序将退出。另外,我没有看到任何超出该行的代码。因此,它也可能是一个正常退出。

0

第一个括号缺失。我想在println之后(“Invalid Input”);

如果仍然没有工作试图抓住各种错误 catch(Exeption e){...}