【问题标题】:Try catch and user input尝试捕获和用户输入
【发布时间】:2013-09-06 23:29:25
【问题描述】:

这是一个涉及 try/catch 块的家庭作业的问题。对于 try/catch,我知道您将要测试的代码放在 try 块中,然后将要发生的代码放在 catch 块中以响应异常,但是在这种特殊情况下我该如何使用它?

用户输入一个存储在 userIn 中的数字,但如果他输入一个字母或除数字之外的任何其他内容,我想抓住它。用户输入的数字将在 try/catch 之后的 switch 语句中使用。

Scanner in = new Scanner(System.in);

try{

int userIn = in.nextInt();

}

catch (InputMismatchException a){

    System.out.print("Problem");

}

switch(userIn){...

当我尝试编译时,它返回符号未找到,对于对应于 switch 语句开头的行号,switch(userIn){。几次搜索后,我发现在 try 块之外看不到 userIn,这可能是导致错误的原因。如何测试 userIn 的正确输入以及让 switch 语句在 try/catch 之后看到 userIn?

【问题讨论】:

  • 问题是“int userIn”是在“try {}”的scope 中定义的。它在该范围之外是不可见的。解决方案:只需移动“int userIn”之前你的“尝试”。

标签: java switch-statement try-catch


【解决方案1】:

int userIntry-catch 作用域内,只能在作用域内使用,不能在作用域外使用。

您必须在try-catch 括号外声明:

int userIn = 0;
try{

userIn = ....
}.....

【讨论】:

    【解决方案2】:

    使用类似的东西:

    Scanner in = new Scanner(System.in);
    
    int userIn = -1;
    
    try {
        userIn = in.nextInt();
    }
    
    catch (InputMismatchException a) {
        System.out.print("Problem");
    }
    
    switch(userIn){
    case -1:
        //You didn't have a valid input
        break;
    

    通过将-1 之类的东西作为默认值(它可以是您在正常运行中不会接收到的任何输入,您可以检查是否有异常。如果所有整数都有效,那么使用可以在 try-catch 块中设置的布尔标志。

    【讨论】:

    • 谢谢,现在可以在 switch 语句中看到 userIn,如果输入了 int 以外的内容,它会返回“问题”。
    • @paulsm4 默认会捕获所有未处理的 int 值(这在任何理智的人的代码中都会很多)。为错误设置一个特定值可以让您更准确地处理错误情况。
    【解决方案3】:

    试试这样的

    int userIn = x;   // where x could be some value that you're expecting the user will not enter it, you could Integer.MAX_VALUE
    
    try{
        userIn = Integer.parseInt(in.next());
    }
    
    catch (NumberFormatException a){
        System.out.print("Problem");
    }
    

    如果用户输入的不是数字,这将导致异常,因为它会尝试将用户输入 String 解析为数字

    【讨论】:

    • 嗯,这不仅不能解决他找不到userIn 的问题,parseInt 还会引发不同的异常,因此您甚至不会在输入中发现错误。跨度>
    • 其实他的问题是在try块外看不到userIn。无论如何,我认为你的解决方案是错误的,in.next() 给出了一个整数,而Integer.parseInt() 需要一个字符串。
    • @pinckerman 你错了,看看这个docs.oracle.com/javase/1.5.0/docs/api/java/util/…
    猜你喜欢
    • 1970-01-01
    • 2015-04-13
    • 1970-01-01
    • 2022-07-01
    • 2017-09-12
    • 2023-03-11
    • 2018-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多