简体   繁体   中英

how to call a different class from within an if/else statement?

I am creating a banking application for my assignment, I would like to know if it's possible to call another class from an if/else statement? if so, where have I gone wrong? as when before compiling I get no errors, but many errors when trying to run. I would like to call the 'public void currentAccountCreate in the currentAccount.java class. I also have a main menu page. many thanks

import java.util.Scanner;

public class Account {
    Scanner keyboard = new Scanner(System.in);

    currentAccount currentAccountCreating = new currentAccount();
    //savingsAccount savingsAccountCreating = new savingsAccount();

    public void accountCreation(){
        String createOption = "";
        boolean valid = false;
        while (!valid) {
            System.out.println("What account would you like to create?");
            System.out.println("Current or savings?");
            createOption = keyboard.nextLine();
            if (createOption.equalsIgnoreCase("current")) {
                currentAccountCreating.currentAccountCreate();
            } else {
                System.out.println("Invalid account type selected. Please enter checking or savings");
            }
        }
    }
}

Here's what I'm trying to call

public class currentAccount extends Account {
    public void currentAccountCreate() {

Error stacktrace

Exception in thread "main" java.lang.StackOverflowError
    at java.util.Currency.getInstance(Unknown Source)
    at sun.util.locale.provider.DecimalFormatSymbolsProviderImpl.getInstance(Unknown Source) at java.text.DecimalFormatSymbols.getInstance(Unknown Source)
    at assignmentmine.Account.<init>(Account.java:7)
    at assignmentmine.currentAccount.<init>(currentAccount.java:5)
    // Plus a load more related ones

You cannot "call" a class, but you can initialize an object of a class and use its public functions. Also, it would be helpful if you said what class you wish to call.

For example, if I have two classes Checking and Savings I would initialize them inside an if/else statement like this:

//pseudocode
if (something)
   Checking obj;
else
   Savings obj;

However, if your question was about creating another instance of the current class, then all you need to do is initialize an object of the current class inside the class itself. Here is an example:

public class Checking {
   Checking obj;
}

Note:

  • The while-loop has no way to stop, it keeps repeating forever!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM