我對Java有點新,最近我學到了很多方法(太酷了!)。我想知道是否有可能在我的主要方法中聲明一個變量並將其用於其他方法。讓一個變量可以通過各種方法訪問
我想要做的是創建一個計算器使用方法(只是爲了實踐這個新的概念),但我不想每次在每個方法中聲明變量。
這裏是代碼的骨骼結構:
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(){
}
}
您應該將值作爲*參數*傳遞給方法。然後這些方法應該*返回結果*。 – RealSkeptic
建議接下來學什麼:嘗試創建一個計算器類,因爲使用'全局變量'當然不是好的做法 – Marged