使所有方法都可以访问变量

Jay*_*reh 0 java variables methods

我对java有点新,我最近学习了一些方法(太酷了!).我想知道是否可以在我的main方法中声明一个变量并在我的其他方法中使用它.

我想要做的是使用方法创建一个计算器(仅用于练习这个新概念)但我不想每次在每个方法中声明变量.

这是代码的骨架结构:

class GS1{



public static void main (String[]args){
    Scanner input = new Scanner(System.in);
    System.out.println("Enter the math operation to be completed: ");
    String opt = input.nextLine();
    int x,y;  // I tried declaring variables here
    switch(opt){

    case  "addition" :
    // addition method goes here
    break;
    case "subtraction":
    //subtraction method goes here
    break;
    case "multiplication":
    //multiplication method   goes  here
    break;
    case "division":
    //division method goes here
    break;
    }

}

static void addition(){
    System.out.println("Enter first value for addition");
    x=input.nextint(); // i get error stating both "x" and "input" cannot be resolved as a variable


}

static void subtration(){


}

static void Multiplication(){

}

static void Division(){



}
Run Code Online (Sandbox Code Playgroud)

}

Mal*_*imi 5

您应该将变量放在所有方法之外但在类中,从而创建全局访问.

public class ClassName
{
    public int x;
    public int y;

    public void method1()
    {
        x = 3;
    }

    public void method2()
    {
        y = 1;
    } 
}
Run Code Online (Sandbox Code Playgroud)

  • 但原来的帖子有静态方法。 (2认同)