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

时间:2015-10-13 21:48:48

标签: java variables if-statement scope gravity

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

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语句的这个公式OUTSIDE

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

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

提前感谢!

2 个答案:

答案 0 :(得分:0)

如果在方法中有上面的代码,那么它的范围仅限于该方法。但是,您可以创建一个类变量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;
     }
}

答案 1 :(得分:0)

只要包含“公式”的语句与“g”的声明在同一个函数/代码块中,就可以引用g作为该语句的一部分。

您应该提供更多详细信息并更明确地描述您的问题。