-2

ok so I need to make this program that involves the gravity constant. but i let the user decide that

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";
}

and then i put it into this formula OUTSIDE of the if statement

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

i know that the scope of the if statement ends after the last curly brace but i'm wondering if there is any way to call for one of the values of g

thanks in advance!

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
MinhazMurks
  • 191
  • 1
  • 2
  • 13
  • 3
    What do you mean by "if there is any way to call for one of the values of g"? What exactly isn't working for you? – Mureinik Oct 13 '15 at 21:51

2 Answers2

0

If you have the above bit of code inside a method, then it's scope is restricted to that method. However you can create a class variable g and set it within your method.

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;
     }
}
Achintha Gunasekara
  • 1,165
  • 1
  • 15
  • 29
  • 1
    I did some more research and set the original initialization of the variable to a final and that fixed my problem! thank you guys very much for taking the time to help me though – MinhazMurks Oct 13 '15 at 22:30
0

As long as your statement containing your "formula" is within the same function/code block as the declaration of 'g', you can reference g as part of that statement.

You should really provide more details and describe your problem more explicitly.

cowdrool
  • 314
  • 1
  • 6
  • I did some more research and set the original initialization of the variable to a final and that fixed my problem! thank you guys very much for taking the time to help me though – MinhazMurks Oct 13 '15 at 22:30