Java:访问Try块中的变量

Java:访问Try块中的变量,java,exception-handling,try-catch,Java,Exception Handling,Try Catch,我知道这个问题已经被问过好几次了,我也试过回答中的建议,但它不适合我的特殊情况 这是供参考的学校作业 我正在编写一个简单的方法来检查用户是否使用try/catch块输入了一个数值。问题是,我的教授对未使用的变量进行了评分,这是有意义的,而我无法找到任何使用userInputValue变量的方法。我尝试在MessageDialog中使用它,但由于它是在Try块中声明的,因此无法访问它。我试着把它移到块外,但后来那个变量就没用了。有没有什么方法可以重写它,但在没有未使用的变量的情况下保留相同的函数

我知道这个问题已经被问过好几次了,我也试过回答中的建议,但它不适合我的特殊情况

这是供参考的学校作业

我正在编写一个简单的方法来检查用户是否使用try/catch块输入了一个数值。问题是,我的教授对未使用的变量进行了评分,这是有意义的,而我无法找到任何使用userInputValue变量的方法。我尝试在MessageDialog中使用它,但由于它是在Try块中声明的,因此无法访问它。我试着把它移到块外,但后来那个变量就没用了。有没有什么方法可以重写它,但在没有未使用的变量的情况下保留相同的函数

public boolean numericalUserInput(String userInput){

    try {
        double userInputValue = Double.parseDouble(userInput);
    }
    catch(NumberFormatException notANumber){
        JOptionPane.showMessageDialog(null, "You entered " + userInput + " but you should only enter numbers, please try again.");
        userEntryTextField.setText("");
        return false;
    }
    return true;
}

谢谢

由于您不需要解析后的数字,因此可以省略赋值:

public boolean numericalUserInput(String userInput){
    try {
        Double.parseDouble(userInput);
    } catch(NumberFormatException notANumber){
        JOptionPane.showMessageDialog(null, "You entered " + userInput + " but you should only enter numbers, please try again.");
        userEntryTextField.setText("");
        return false;
    }

    return true;
}

似乎您不需要使用userInputValue,因为您仅使用此方法来检查userInput字符串是否为数字。您只需像这样离开userInputValue:

public boolean numericalUserInput(String userInput){

    try {
        Double.parseDouble(userInput);
    }
    catch(NumberFormatException notANumber){
        JOptionPane.showMessageDialog(null, "You entered " + userInput + " but you should only enter numbers, please try again.");
        userEntryTextField.setText("");
        return false;
    }
    return true;
}

在您的方法中,不需要变量来携带parse double方法的返回值

public boolean numericalUserInput(String userInput){

try {
    Double.parseDouble(userInput);
}
catch(NumberFormatException notANumber){
    JOptionPane.showMessageDialog(null, "You entered " + userInput + " but you should only enter numbers, please try again.");
    userEntryTextField.setText("");
    return false;
}
return true;
}
如果您需要返回的号码,您可以更改您的方法以使用该号码,如下所示

public double numericalUserInput(String userInput){
     double userInputValue;
try {
    userInputValue = Double.parseDouble(userInput);
}
catch(NumberFormatException notANumber){
    JOptionPane.showMessageDialog(null, "You entered " + userInput + " but you should only enter numbers, please try again.");
    userEntryTextField.setText("");
    return Double.NaN;
}
return userInputValue ;
}

为什么有这个变量呢?只需调用
Double.parseDouble(userInput)并完成它。将您的代码放在您想使用的
userInputValue
中block@SteffenKreutz我不知道为什么,但它以前不是这样工作的,我必须同时重新格式化一些其他代码。现在是这样的。谢谢大家!@azurefrog由于某种原因,它以前没有这样工作,但现在它是。我一定是修改了我玩的其他代码。现在可以用了,谢谢!