有没有办法从特定的 if 语句中调用变量?

is there any way to call a variable from a specific if statement?

好的,所以我需要制作这个涉及重力常数的程序。但我让用户决定

double g;
String unit;

if (n == JOptionPane.YES_OPTION) {
    g = 9.8;
    System.out.print(g);
    unit = "meters/s";
}
else {
    g = 32;
    System.out.print(g);
    unit = "feet/s";
}

然后我将它放入 if 语句之外的公式中

double ycoord = (velo0*sinF*time)-((g)((time*time)))/2;

我知道 if 语句的范围在最后一个大括号之后结束,但我想知道是否有任何方法可以调用 g

的值之一

提前致谢!

如果你在一个方法中有上面的代码,那么它的范围仅限于该方法。但是,您可以创建一个 class 变量 g 并在您的方法中设置它。

Public Class Test {

     //g can only be accessed within this class
     //however you can access g with the following getter method
     private double g;

     public static void setG() {

          this.g = 9.5;
     }

     public static void setGWithInput(Double input) {

          this.g = input;              
     }

     public static void printG() {

          //you can access the value of g anywhere from your class
          System.out.println("Value of g is" + this.g);
     }

     //create a public getter to access the value of g form outside the class
     public double getG() {

          return this.g;
     }
}

只要包含 "formula" 的语句与 'g' 的 声明 在同一个 function/code 块中,您就可以参考g 作为该声明的一部分。

你真的应该提供更多细节并更明确地描述你的问题。