2014-11-06 47 views
0

我是Java新手,創建了調用另一個名爲BankAccount的類的類,在編譯時出現「找不到符號」錯誤,該方法正好在下面我的主要。任何幫助將是偉大的,謝謝。在BankAccount項目中找不到createAccount符號

import java.util.Scanner; 
public class InClass 
{ 
    public static void main (String []args) 
    { 
     BankAccount account; 

     account = new createAccount(); 

    } 

    public BankAccount createAccount() 
    { 
     Scanner kb = new Scanner (System.in); //input for Strings 
     Scanner kb2 = new Scanner (System.in); //input for numbers 
     String strName;       //Holds account name 
     String strAccount;      //Holds account number 
     String strResponse;       //Holds users response to account creation 
     double dDeposit;      //Holds intial deposit into checking 
     BankAccount cust1; 

     System.out.print ("\nWhat is the name of the account? "); 
     strName = kb.nextLine(); 
     while (strName.length()==0) 
     { 
      System.out.print ("\nPlease input valid name."); 

      System.out.print ("\nWhat is the name of the account?"); 
      strName = kb.nextLine(); 
     } 

     System.out.print ("\nWhat is your account number?"); 
     strAccount = kb.nextLine(); 
     while (strAccount.length()==0) 
     { 
      System.out.print ("\nPlease enter valid account number."); 
      System.out.print ("\nWhat is your account number?"); 
      strAccount = kb.nextLine(); 
     } 

     ...... 

     return cust1; 
} 
+0

您不需要使用新的關鍵字'account = new createAccount();'。這就是調用一個類的構造函數 – sunrize920 2014-11-06 18:35:22

回答

0

如果你想有一個非靜態方法,你可以改變

account = new createAccount(); 

account = new InClass().createAccount(); 

因爲createAccount()方法也不是一成不變的,它需要一個周圍類的實例。 new InClass()創建一個實例。

+0

謝謝你,解決方案的工作原理。現在想弄清楚如何撥打我的BankAccount類。再次感謝。 – ph0bolus 2014-11-06 18:50:21

+1

@ ph0bolus:你不叫一個類 - 你在一個類中調用*方法*。 – 2014-11-06 19:07:17

+0

@JonSkeet是的,這就是我的意思。仍然習慣於詞彙。 – ph0bolus 2014-11-06 20:53:05

1

這就是問題所在:

account = new createAccount(); 

那不是試圖調用一個方法叫做createAccount - 它試圖呼叫被叫createAccount類型的構造函數,你沒有這樣的類型。

您可以這樣寫:

account = createAccount(); 

...但隨後會失敗,因爲createAccount實例方法,而不是一個靜態方法(和你沒有的InClass一個實例來調用它上)。你可能希望它是一個靜態方法。

作爲一個側面說明,我會強烈建議您在首次使用時聲明變量,並擺脫僞匈牙利符號,例如,

String name = kb.nextLine(); 

代替:

String strName; 
... 
strName = kb.nextLine(); 

在Java中,你不需要在方法的頂部宣佈所有局部變量 - 而這樣做傷害了可讀性。

+0

儘管指令要求提供一個非靜態的createAccount方法。是的,我知道閱讀很痛苦,但我的老師很老派,並且從一開始就介紹了匈牙利語。 – ph0bolus 2014-11-06 18:38:54

+0

@ ph0bolus:在這種情況下,你需要創建一個'InClass'的實例,儘管它沒有意義。即使你*使用匈牙利符號(ick),你仍然不需要在方法頂部聲明變量... – 2014-11-06 19:06:56

0

createAccount方法是非靜態的並且與InClass類相關聯。爲了調用該方法,您需要一個InClass的實例。也許是這樣的:

public static void main(String[] args) { 
    InClass inClass = new InClass(); 
    BankAccount account = inClass.createAccount(); 
}