有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java有没有办法从特定的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;

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

提前谢谢


共 (2) 个答案

  1. # 1 楼答案

    如果在一个方法中包含上述代码,那么它的作用域仅限于该方法。但是,您可以创建一个类变量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;
         }
    }
    
  2. # 2 楼答案

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

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