0

我是 Java 的初学者,正在尝试捕获异常“InputMismatchException”。以下是我的代码,希望它易于阅读,如果格式不正确,请提前道歉。它构建良好并执行,但是如果我输入一个字符,例如“catch”不起作用并且出现错误;

“线程“主”java.util.InputMismatchException 中的异常”

我相信代码中的所有其他内容都可以正常工作,包括“尝试”,除了 System.out.print 命令之外,我没有任何内容。

import java.util.*; // imports

public class w4q1

    {
        public static void main(String[] args)
        {
            Scanner user_input = new Scanner( System.in ); // declaring Scanner util
                System.out.print("Please enter an integer: \n"); // Asks for input
                int d = user_input.nextInt();

        while (d > 0 || d < 0) // start of while loop, in the event of anything other than zero entered
        {
            try {

                    if (d < 0) // if statements
                    {
                    System.out.print("The integer " + d + " is negative\n");
                    break;
                    }

                            else if (d > 0)
                            {
                            System.out.print("The integer " + d + " is positive\n");
                            break;
                            }

                                else 
                                {
                                System.out.print("You have not entered an integer\n");
                                break;
                                }

                }

                catch (InputMismatchException e) // Error message for letters/characters and decimals
                    {
                        System.out.print("You have entered an incorrect value, please restart the program\n");
                    }



        }

        if (d == 0)
            {
            System.out.print("A zero has been entered\n");
            }

        }
    }   
4

3 回答 3

1

如果即使您有一个 try-catch 块,您仍然收到一个InputMismatchException异常,那么异常必须来自您的 try-catch 块之外的某个地方。

查看 try-catch 块之外的其他内容可以抛出一个InputMismatchException并在该语句周围放置一个 try-catch 块,或者扩展您现有的 try-catch 块以包含该语句。

于 2013-10-23T16:58:22.957 回答
0

如果确实没有捕获到异常,那么生成的堆栈跟踪应该向您显示引发异常的实际代码行。查看代码,我猜这是发生异常的地方:

 user_input.nextInt();

我建议您查看堆栈跟踪,看看您是否可以确认这一点。

于 2013-10-23T17:06:11.347 回答
0

在此代码周围放置一个 try-catch 块

int d = user_input.nextInt();

通过这样做,您还需要稍微更改当前代码以使其正常。祝你好运 !

于 2014-09-24T06:19:43.927 回答