Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/356.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在块外使用变量(在try/catch块内)?_Java_Methods_Try Catch_Java.util.scanner_Do While - Fatal编程技术网

Java 如何在块外使用变量(在try/catch块内)?

Java 如何在块外使用变量(在try/catch块内)?,java,methods,try-catch,java.util.scanner,do-while,Java,Methods,Try Catch,Java.util.scanner,Do While,我试图使用try/catch块,但无法从块中获取变量值。 我能做什么 import java.util.Scanner; public class Program { public static void main(String[] args) { System.out.print("Enter a number : "); returnValue(); System.out.println(returnValue()); }

我试图使用try/catch块,但无法从块中获取变量值。 我能做什么

 import java.util.Scanner;

public class Program {

    public static void main(String[] args) {
        System.out.print("Enter a number : ");
        returnValue();
        System.out.println(returnValue());
    }

    public static int returnValue() {
        Scanner imp = new Scanner(System.in);
        boolean loP = true;
        do {
            String num = imp.next();
            try {
                int Nums = Integer.parseInt(num);
                loP = false;
            } catch (Exception e) {
                System.out.print("Please enter a number : ");
            }
        } while (loP);
        imp.close();
    }
}

您只需要使用所需的。例如,只需在声明
loP
变量的位置声明
Nums
变量。

只需在块外声明它们并给它们一个默认值

public static int returnValue(){
    Scanner imp = new Scanner(System.in);
    boolean loP = true;
    int Nums =0; //declare them outside the try...catch block and give them a default value
    do {
        String num = imp.next();
        try {
           Nums = Integer.parseInt(num);
            loP = false;
        } catch (Exception e) {
            System.out.print("Please enter a number : ");
        }
    } while (loP);
    imp.close();
    }
    }

在类上使用私有int。并从try/catch部分进行更新。您可以从任何函数中使用它

public class program{
 private int something;
 public int somemorething;
}
尝试使用以下方法:

public static void main(String[] args) {
    System.out.print("Enter a number : ");
    System.out.println(returnValue());
    System.out.print("Enter a number : ");
    System.out.println(returnValue());
}

public static int returnValue() {
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
    do {
        try {
            String num = bufferedReader.readLine();
            return Integer.parseInt(num);
        } catch (Exception e) {
            System.out.print("Please enter a number : ");
        }
    } while (true);
}

在returnValue()方法的开头用一些初始值声明变量,否则它将显示“永不初始化”警告,将来它将帮助您进行调试。

在块外声明它们,就像声明其他变量一样。