2015-10-13 159 views
-2

好,所以我需要使这个程序涉及重力恒定。但我让用户决定有没有办法从特定的if语句中调用变量?

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; 

我知道,如果报表范围的最后一个大括号后结束,但我想知道是否有任何方式来呼吁g的值之一

在此先感谢!

+3

你是什么意思“如果有任何方法来调用g的值之一”?什么不适合你? – Mureinik

回答

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”的声明内,可以引用克作为语句的一部分。

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

+0

我做了一些更多的研究,并将变量的初始化设置为最终并解决了我的问题!非常感谢你们花时间帮助我 –

相关问题