try catch块中的变量范围

时间:2014-11-08 20:34:19

标签: java variables scope try-catch console-application

我正在通过命令行创建一个用户界面,它会询问1-4的选项,我想要进行错误检查。只允许1到4之间的整数。这是我到目前为止的代码。我希望该方法将userInput整数返回给另一个用它做一些事情的方法。

package contactmanager;

import java.util.InputMismatchException;
import java.util.Scanner;

/**
 *
 * @author andyjohnson
 */
public class UserInterface {

    public static Integer GetInput() {
        Scanner in = new Scanner(System.in);
        //Integer userInput;
        System.out.println("Welcome to the contact manager\nMake a selection below:");
        System.out.println("1)Display Contacts\n2)Add new business contact\n3)Add new personal contact\n4)Quit");
        try {
            Integer userInput = in.nextInt();
            if (userInput < 1 || userInput > 4) {
                System.out.println("Please enter a valid selection");
                UserInterface.GetInput();
            }

        } catch (InputMismatchException e) {
            e.getMessage();
            System.out.println("Please enter a valid selection");
            UserInterface.GetInput();
        }

        return userInput;

    }

}

我的返回语句在IDE中有下划线,并且告诉我它没有被初始化。我想全局初始化它,但允许try语句更改值。我已经尝试过.userInput = userInput但我无法弄清楚我的范围被破坏了。如何给try块全局范围?我是java的新手,所以任何事情都有帮助。谢谢!

2 个答案:

答案 0 :(得分:0)

您可以在try-catch块之外声明userInput变量:

package contactmanager;

import java.util.InputMismatchException;
import java.util.Scanner;

public class UserInterface {

    public static Integer GetInput() {
        Scanner in = new Scanner(System.in);
        System.out.println("Welcome to the contact manager\nMake a selection below:");
        System.out.println("1)Display Contacts\n2)Add new business contact\n3)Add new personal contact\n4)Quit");
        Integer userInput = null;
        try {
            userInput = in.nextInt();
            if (userInput < 1 || userInput > 4) {
                System.out.println("Please enter a valid selection");
                UserInterface.GetInput();
            }

        } catch (InputMismatchException e) {
            e.getMessage();
            System.out.println("Please enter a valid selection");
            UserInterface.GetInput();
        }

        return userInput;

    }

}

答案 1 :(得分:0)

try-catch块的范围与仅与方法的其余部分一致编写代码的范围不同。

我认为您遇到的问题是在userInput块中首先声明变量try-catch的这一行:

Integer userInput = in.nextInt();

这是一个问题的原因:

考虑try-catch块是否失败。什么会被退回?变量userInput甚至没有定义,因此Java不知道要返回什么。

修复相对简单。您只想将其移出try-catch块,就像这样。这应该摆脱你的return错误。我注意到你评论了这个改变。为什么呢?

但我还有一个建议。你为什么打电话给UserInterface.GetInput()?为什么不让方法接受有效输入的参数,如果数据格式不合适,就不要调用它?你用它吗?这将消除对真正全局范围变量的需求。

由于编写此方法的方式,它必须返回某种类型的Integer,除非您编写该方法,因为该方法会抛出在下游某处捕获的异常。

我试图做一些我认为最有意义的修复:

Scanner in = new Scanner(System.in);
Integer userInput; // Integer representation of user input

try {
    Integer a = in.nextInt(); // if a can be assigned to an Integer this line work
    if (a < 1 || a > 4) {
        // called if the input can be assigned to an Integer and is within the range
        userInput = a;
    }

} catch (InputMismatchException e) {
    // otherwise the catch block is called
    System.out.println("Please enter a valid selection");
}

return userInput;

也许您想在范围检查中调用UserInterface.GetInput()?希望这有帮助!

编辑:使用sentinel标志而不是调用方法

Scanner input = new Scanner(System.in);
System.out.println("Please enter a valid Integer.  When done type DONE ");

// this method will keep cycling until the String DONE is typed
// you could make this condition whatever you want
while (!input.hasNext("DONE")) {

    String a = input.next(); // gets the next item from the Scanner

    try {
        Integer b = Integer.parseInt(a); // tries to 'cast' the String to an Integer

        if (b < 1 || b > 4) {
            System.out.println("Input is valid!");
        } else {
            System.out.println("Input is invalid!");
        }

    } catch (NumberFormatException e) {
        System.out.println("Please enter a valid selection!");
    }
}