0

I'm attempting to practice classes methods since I'm very new to JAVA. In my full program I am using other global variables and they are working fine within my other methods. My question is how do i get the public String y to work inside the parameters of my isNum() method so that inside any method I can use isNum(y); The way it is now the String y is only within the scope of isNum but I want y to be global inside the paramters of isNum and within it. Simple answers as possible thank you so much.

public static String y;
public static boolean isNum(String y){

for(int i = 0; i < y.length(); i++){

if(!(y.charAt(i) >= 48 && y.charAt(i) <= 57)){

    return false;
    }
}

return true;

} 

I want to use isNum in this loop and transfer the value of x into y. I know x is an int and y is a string. How would I make that work?

        x = input.nextInt();

        if(isNum(y){
        while(x <=0 || x > 3){
             System.out.println("Choose a correct gear number: ");

             x = input.nextInt();
        }
        switch(x){
            case 1:
            System.out.println("You're in Gear 1");
                break;
            case 2:
            System.out.println("Gear 2");
                break;

            case 3:
            System.out.println("Gear3");
        }
      }

    }
1
  • 1
    java doesn't have functions, nor global variables. Commented Jan 26, 2016 at 7:34

3 Answers 3

2

If you want isNum to access the static y variable, qualify it with the class name - ClassName.y.

When you write the unqualified variable name y inside your method, the local variable y hides the static variable of the same name.

EDIT : After re-reading your question, I'm not sure if your isNum method even needs to have the y parameter. If you want that method to use the static variable y, you can simply change its signature to public static boolean isNum() and leave the method body unchanged.

Sign up to request clarification or add additional context in comments.

Comments

2

global variables don't have to put into function.just use them directly!
In one class,use them directly.
In another class,use ClassName.var.

Comments

0

it is not clear what you are trying to do.... if the function will always check if the "global" variable y is a number you should simply create a class like this:

public class global
{
    private static String y;

    public static boolean isNum(){...}//no need to get y as parameter
}

The thing you should pay attention to is that Java is Object Oriented so you can't just have a global variable on it's own... it should be a static variable in a class that has static methods to deal with that variable

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.