簡體   English   中英

如何從if / else語句中調用不同的類?

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

我正在為我的作業創建銀行業務應用程序,我想知道是否可以從if / else語句中調用另一個類? 如果是這樣,我哪里出錯了? 就像在編譯之前一樣,我沒有收到任何錯誤,但是在嘗試運行時卻出現了很多錯誤。 我想在currentAccount.java類中調用'public void currentAccountCreate。 我也有一個主菜單頁面。 非常感謝

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");
            }
        }
    }
}

這是我要打電話的內容

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

錯誤堆棧跟蹤

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

您不能“調用”一個類,但是可以初始化一個類的對象並使用其公共功能。 另外,如果您說自己想打的是什么課這將是有幫助的。

例如,如果我有兩個CheckingSavings類,我將在if / else語句中將它們初始化,如下所示:

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

但是,如果您的問題是關於創建當前類的另一個實例,那么您要做的就是在類本身內部初始化當前類的對象。 這是一個例子:

public class Checking {
   Checking obj;
}

注意:

  • while循環無法停止,它會一直重復下去!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM