我正在創建一個程序,該程序包含具有某些關聯字段和方法的Count對象。Java:使用先前方法中構造的對象
在程序中,Count對象在setupCounter()方法中初始化,而其方法實際在counterControl()方法中使用。但是,當我嘗試調用我以前在setupCounter()方法中初始化的Count實例時,我被告知「count無法解析」,因此我假設創建的Count的實例僅具有本地作用域。
有誰知道如何克服Counter實例的範圍不足的問題?以下是我的代碼:
import java.util.Scanner;
public class Main {
static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
setupCounter();
for (;;) {
counterControl();
}
}
public static void setupCounter() {
int startVal;
int incrementVal;
System.out.println("Please enter the starting value of the counter:");
startVal = in.nextInt();
System.out.println("Please enter the increment/decrement amount on the counter:");
incrementVal = in.nextInt();
Count count = new Count(startVal, incrementVal);
}
public static void counterControl() {
String control;
System.out.println("The following controls can be applied to the counter:");
System.out.println("Increment - i");
System.out.println("Decrement - d");
System.out.println("Exit - x");
control = in.nextLine();
switch (control) {
case "i":
count.increment();
break;
case "d":
count.decrement();
break;
case "x":
System.exit(0);
break;
}
}
}
謝謝。