2017-09-25 9 views
-2

定義済みのハッシュテーブルにアイテムを追加する場合、通常は単純です。しかし、私がaddNewCustomer()のようなメソッドを定義し、そのメソッド内でcustomerHashtable.put(...);関数を使用しようとすると、機能しません。既存のハッシュテーブルで動作するメソッドを定義し、新しいオブジェクト(この場合は顧客)を追加できるようにしてください。ここでJavaで既存のハッシュテーブルに新しい項目を入力するメソッドを定義する方法は?

は、以下のコードは次のとおりです。

public static void main(String[] args) { 

      Hashtable<Integer, Customer> customerHashtable = new Hashtable<Integer, Customer>(); 
      customerHashtable.put (1, new Customer("david", "+13035003433", new Address("AR", "77555"))); 

      Customer customer = new Customer("mark", "13035003433", new Address("AR", "77200")); 

      public void addNewCustomers(int key, Customer customer) { 
      customerHashtable.put(key, customer); 
      System.out.println(customerHashtable.get(key).toString()); 
      } 
    } 

} 
+0

関数に 'customerHashtable'を渡すか、クラスフィールドにする必要があります。 –

+1

それはうまくいかないという意味ですか?より具体的になりますか? –

+0

@ElliottFrisch私はプログラミングに慣れていないのです。もう少し説明していただけますか?私はまた、上記で達成したいコードをコピーしました。 –

答えて

0

あなたのmain方法の外に、あなたのaddNewCutomers()方法を入れて、あなたのHashTableのクラスフィールドを作成する必要があります。静的コンテキストで大丈夫だと仮定すると、次のようになります。

public class HashtableDemo { 

    static Hashtable<Integer, Customer> customerHashtable; 

    public static void main(String[] args) { 

     customerHashtable = new Hashtable<Integer, Customer>(); 
     customerHashtable.put (1, new Customer("david", "+13035003433", new Address("AR", "77555"))); 

     Customer customer = new Customer("mark", "13035003433", new Address("AR", "77200")); 
     addNewCustomers(2, customer); 
    } 

    public static void addNewCustomers(int key, Customer customer) { 
     customerHashtable.put(key, customer); 
     System.out.println(customerHashtable.get(key).toString()); 
    } 
} 
+0

固定していただきありがとうございます。出来た。私は1つの質問がある。静的メソッドを使用しているので、他のクラスからそのメソッドを呼び出すこともできますか? @TobiasGeiselmann –

+0

正しい。 'public'メソッドなので、他のクラスから呼び出すこともできます。 –

+0

もう一度ありがとうございます。 –

関連する問題