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
答案 0 :(得分:0)
请注意,您有一些范围错误 - 在方法内部声明的变量仅在该方法中可见,并且在其他方法中不可见。要解决这个问题,您可以在类中声明变量。
例如,仅使用静态字段和方法:
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()
方法。