2016-11-01 6 views
-2

私は、強化されたforループステートメントの値をしばらく印刷して、それを行う方法を理解できないように見える方法を見つけようとしています。私は強化されたforループの基本的な概念を理解していますが、私のシナリオでどのように使用するのか分かりません。ここで強化されたforループを使用してArrayListの値を出力する方法はありますか?

はコードです:

import java.util.ArrayList; 

public class userGroup { 

    ArrayList<User> userGroup = new ArrayList<>(); 
    User user0; 

    public void addSampleData() { 

    userGroup.add(user0); 

    } 

    public void printusername(){ 

     for (User x: userGroup) 
      System.out.println(x); 
    } 
} 

どのように私はのUser0とその値を出力printusername方法でforループ文を実装するのでしょうか?私はおそらく、ArrayListの作成のどこかにエラーがあるので、私は理解していますが、どこにエラーがあるのか​​分かりません。私と他の誰かが同じ問題を抱えていると、どんな助けも大いに評価されます。ありがとう。

+1

1明白な問題は...あなたのUser0オブジェクトがnull参照であるので、最終的にされますarraylistにnullを追加しています – mhasan

+1

1. generics: 'ArrayList 'を使うべきです。 2. 'getUser'はおそらくあなたが思っていることをしません。 3. 'for'ループで試したことを投稿します。 – bradimus

+0

クラスの名前をメンバーの名前と同じにしないでください。また、Javaでは、クラス名の先頭が大文字で始まるという規則があります。 userGroupではなくUserGroup。 – azurefrog

答えて

0

私はあなたが答えに近づいていると考えていますが、ケースを少し簡単にしましょう。いくつかのポイントを取得するための1つの方法だけで、同様のケースを示しましょう。

public void printUsername() { //note the case. this is by convention in Java. 

     //The left side is using the Collection interface, not an ArrayList. 
     //This is the weakest interface that we can use. 
     //We are also using generics to show that we have a Collection of User objects. 

     //Lastly, we include the number one to show that we are 
     //creating an ArrayList with an initial capacity of 1. We are just 
     //adding one object. 

     Collection<User> userGroup = new ArrayList<>(1); 

     //We create an object by using the "new" keyword 
     User user0 = new User(); 

     //and now we add it to the Collection we created earlier 
     userGroup.add(user0); 

     //now iterate through the loop 
     for (User user: userGroup) { //note the use of braces for clarity 
      //this will call toString on the User object 
      //if you don't implement toString(), 
      //you'll get a rather cryptic address (technically, a hashcode of the object) 

      //try to make your variable names mean something too. 
      //it's much easier to track down issues later when your variable 
      //names make sense. And it's much easier for the next person 
      //trying to make sense of your code. 
      System.out.println(user); 
     } 
    } 

は、Java 8を使用しているか、後で、あなたはコレクトコールと拡張forループを置き換えることができた場合:

userGroup.forEach(System.out::println); 
関連する問題