java - 在 if 语句内创建对象

标签 java if-statement constructor scope

我正在尝试为银行帐户编写一个简单的程序。我创建了一个名为 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/

相关文章:

java - 打印能被2整除但不能被3整除的数字?

r - 在 R 中格式化电话号码

android - 自定义 SurfaceView 导致 NoSuchMethodException

java - 在 finally block 中,我可以判断抛出了什么异常吗?

java - 基数排序 Java 实现

javascript - Javascript 中 boolean 语句是如何计算的

c++ - 使用类似于 strndup 的语义从 char[] 创建 std::string

javascript - 重定义构造函数原型(prototype)后,对象构造函数指向原始构造函数而不是prototype.constructor

java - EL枚举字符串处理

Java:从 JAR 文件中的类文件中获取方法 stub 的简单方法?反射?