使变量可被所有方法访问 [英] Make a variable accessible by all methods
本文介绍了使变量可被所有方法访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对 Java 有点陌生,我最近学习了方法(太酷了!).我想知道是否可以在我的 main 方法中声明一个变量并在我的其他方法中使用它.
I'm a bit new to java and i recently learned about methods(so cool!). I want to know if its possible to declare a variable in my main method and use it in my other methods.
我想要做的是使用方法创建一个计算器(只是为了练习这个新概念)但我不想每次在每个方法中都声明变量.
What i am trying to do is create a calculator using methods(just for practice with this new concept) but i dont want to declare the variable every time in each method.
这是代码的骨架结构:
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(){
}
}
推荐答案
你应该把变量放在所有方法之外,但放在类内,创建全局访问.
You should place the variable outside of all methods but within the class, creating global access.
public class ClassName
{
public int x;
public int y;
public void method1()
{
x = 3;
}
public void method2()
{
y = 1;
}
}
这篇关于使变量可被所有方法访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文