在if语句内创建对象 [英] Creating an object inside an if statement

查看:78
本文介绍了在if语句内创建对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为银行帐户编写一个简单的程序.我已经创建了一个名为Bank的类来制作和实例,并在主类的主要方法中创建了一个if语句,该语句将根据满足的条件创建"Bank"类的实例.问题是我可以使用if语句之外的实例方法.我为对象类创建了两个构造函数,一个具有构造函数方法参数,另一个没有任何参数,这就是使用if语句的原因.

I'm trying to make a simple program for a bank account. I have created a class called Bank to make and instance and in the main class, where the main method is, I have made an if statement which will create an instance of the class "Bank" depending on the conditions met. The problem is that I can use the instance methods, which is outside the if statement. I have created two constructors for the object class, one with a constructor method parameter and another method which doesnt take any parameters, which is the reason of using an if statement.

 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子句中.应该更改为:

your Bank object will only live in if clause. should change to :

Bank account1 = null;
if (clause){
    account1 = new Bank();
}else{
  ...
}

这篇关于在if语句内创建对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆