2016-11-07 7 views
0

私はプログラミングが初めてです。私はそれに約150の文字列を持つ値という名前の文字列配列を持っています。大量のif文を使用するのではなく、forループを使用してループを繰り返すたびに、配列内の次の要素にループがインクリメントされます。私はそれが超簡単な修正だと確信していますが、私はそれを解決できません。アドバイスありがとう!Java - forループの文字列配列を循環

routeListView.setOnItemClickListener(
      new AdapterView.OnItemClickListener() { 
       @Override 
       public void onItemClick(AdapterView<?> parent, View view,  int position, long id) { 

        String route = values[position]; 

        int i; 
        for (i=0; i < values.length;i++) { 

         if (route.equals(values[0])) { 

          Intent intent = new Intent(view.getContext(), RouteDetails.class); 
          intent.putExtra("route", routeDetail[0]); 
          startActivity(intent); 
         } 
        values++; 
        } 
        /*if (route.equals(values[0])) { 

         Intent intent = new Intent(view.getContext(), RouteDetails.class); 
         intent.putExtra("route", routeDetail[1]); 
         startActivity(intent); 

        } 
        if (route.equals("Main Wall")) { 

         Intent intent = new Intent(view.getContext(), RouteDetails.class); 
         intent.putExtra("route", "Map of Main Wall"); 
         startActivity(intent); 

        } 
        if (route.equals("1. Shark Bait - 5.9")) { 

         Intent intent = new Intent(MainActivity.this,  RouteDetails.class); 
         intent.putExtra("route", "Shark Bait"); 
         startActivity(intent); 

        } 
*/ 
       } 
+0

このコードはコンパイルできますか? 'values'は' String [] 'ですが、' values ++ 'を使ってどのようにインクリメントできますか? –

答えて

0

ループの内側で、ハードコードされた0を "i"に置き換えます。これにより、ループの繰り返しごとにコードを実行することができます。それはI ++中で扱われているので、例えば、私は、等

for (int i=0; i<values.length; i++) { 

if (route.equals(values[i])) { 

    Intent intent = new Intent(view.getContext(), RouteDetails.class); 
    intent.putExtra("route", routeDetail[i]); 
    startActivity(intent); 
} 
} 

また、終了時に値のカウンタを追加する必要がない、次いで0、1、2で置換されforループ。希望が助けてくれる!

+0

おかげであなたは完璧に動作します! – user4297729

0

スイッチを使用できるようです... intとstringの両方の比較が必要な場合は、2つのスイッチを使用してそれを行うことができます。

String route = values[position]; 

    switch(position) { 
     case 0: 
      Intent intent = new Intent(MainActivity.this, RouteDetails.class); 
      intent.putExtra("route", routeDetail[0]); 
      startActivity(intent); 
      return; 
     case 1: 
      // Do stuff 
      return; 
    } 

    switch(route) { 
     case "Main Wall": 
      Intent intent = new Intent(MainActivity.this, RouteDetails.class); 
      intent.putExtra("route", "Map of Main Wall"); 
      startActivity(intent); 
      return; 

     case "Shark Bait": 
      Intent intent = new Intent(MainActivity.this, RouteDetails.class); 
      intent.putExtra("route", "Shark Bait"); 
      startActivity(intent); 
      return; 
    } 
+0

ありがとうございます。だから、if文やswitch文のように150を使う必要はありません。 – user4297729

関連する問題