我正在尝试为银行帐户编写一个简单的程序。我创建了一个名为 Bank 的类来创建实例,并在主类(主要方法所在)中创建了一个 if 语句,该语句将根据满足的条件创建类“Bank”的实例。问题是我可以使用实例方法,该方法位于 if 语句之外。我为对象类创建了两个构造函数,一个带有构造函数方法参数,另一个方法不带任何参数,这就是使用 if 语句的原因。
public static void start() {
Scanner scanner = new Scanner(System.in);
System.out.println("Welcome to your banking app!");
System.out.println("What is your initial balance, enter below. If none enter : n");
String choice = scanner.nextLine();
if(choice.equals("n")){
Bank account1 = new Bank();
}
else{
System.out.println("Enter your initial balance :");
double ibalance = scanner.nextDouble();
Bank account1 = new Bank(ibalance);
}
System.out.println("Enter 1 to see balance Enter 2 to withdraw Enter 3 to deposit money Enter 4 to close account Enter 5 to exit");
choice = scanner.nextLine();
double amount = 0.0;
if(choice.equals("1")){
System.out.println("Balance is :" + account1.getBalance());
}
else if(choice.equals("2")){
System.out.println("Enter the amount to withdraw");
amount = scanner.nextInt();
account1.withdraw(amount);
}
else if(choice.equals("3")){
System.out.println("Enter the amount to deposit");
amount = scanner.nextInt();
account1.deposit(amount);
}
else if(choice.equals("4")){
account1.close();
}
else if(choice.equals("5")){
System.exit(0);
}
}
最佳答案
您的 Bank 对象仅存在于 if 子句中。应更改为:
Bank account1 = null;
if (clause){
account1 = new Bank();
}else{
...
}
关于java - 在 if 语句内创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44022664/