我有点迷茫;我觉得我之前已经做过类似的事情,但这是行不通的。我忘记了一些调整吗?由于某种原因,它说它找不到下面的三个变量,我是否需要将它们移到其他位置/在方法中声明/以某种方式使方法与变量调用脱节?所有帮助,不胜感激。
Scanner input = new Scanner(System.in);
int atmId, selection;
double atmVal;
selectId();
switch(selection){
case 1: AccArray[atmId].getBalance();
break;
case 2: System.out.print("How much would you like to withdraw? ");
atmVal=input.nextInt();
AccArray[atmId].withdraw(atmVal);
break;
case 3: System.out.print("How much would you like to deposit? ");
atmVal=input.nextInt();
AccArray[atmId].deposit(atmVal);
break;
case 4: selectId();
break;
}
} // End of main method
// Method for id selection
public static void selectId(){
// Allows for and requests user input
System.out.print("Enter an id: ");
atmId = input.nextInt();
// Checks for valid input
while (atmId>9 || atmId<0){
System.out.println("Invalid id.");
System.out.print("Enter an id (0-9): ");
atmId = input.nextInt();
}
displayMenu();
}
// Method to display menu
public static void displayMenu(){
System.out.println("Main menu");
System.out.println("1: check balance");
System.out.println("2: withdraw");
System.out.println("3:deposit");
System.out.println("4:exit");
System.out.print("Enter a choice ");
selection = input.nextInt();
// Checks for valid input
while (selection>4 || selection<1){
System.out.println("Invalid choice.");
System.out.print("Enter a choice (1-4): ");
selection = input.nextInt();
}
}
} // End of Test class
最佳答案
请注意,您存在一些范围界定错误-在方法内部声明的变量仅在该方法内可见,而在其他方法中不可见。为了解决这个问题,您可以在类中声明变量。
例如,仅使用静态字段和方法:
public class Foo {
private static int bar; // I am visible throughout the class
public static void someMethod() {
int baz = 8; // I've declared a *local* variable here
}
public static void anotherMethod() {
bar = 3; // I can use bar here since it's visible throughout
baz = 7; // this won't compile since baz is visible only within someMethod()
}
}
话虽如此,但是您的
selectId()
方法不应该返回一个int吗?然后,您不应该将返回的int分配给选择变量吗?如果这样做,则不必在类中声明选择变量。请注意,我将让
displayMenu()
做到这一点-显示菜单,并且不会让它得到用户输入。那将是selectId()
方法要做的。
关于java - 找不到符号错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23050140/