2016-03-31 12 views
0

現在、配列投票者を保持している「投票者」クラスの配列内の個々のフィールドを更新しようとしています。別のクラスで配列のインデックスを更新する方法

import java.io.File; 
import java.io.FileNotFoundException; 
import java.util.Scanner; 

public class Proj06_Voting 
{ 
    public static void main(String[] args) 
     throws FileNotFoundException 
    { 
     if (args.length != 1) 
     { 
      System.out.println("Class requires 1 argument"); 
      return; 
     } 

     Voter[] voters = new Voter[12]; 
     String[] candidate = new String[5]; 
     int[] selection = new int[12]; 
     File inFile = new File(args[0]); 
     Scanner in = new Scanner(inFile); 

     System.out.println("THESE ARE THE VOTERS:"); 
     for(int i=0; i<5; i++) 
     { 
      candidate[i] = in.next(); 
     } 
     for(int i=0; i<12; i++) 
     { 
      voters[i].name = in.next(); 
      for(int j=0; j<5; j++) 
      { 
       voters[i].preference[j] = in.next(); 
      } 
      System.out.print(voters[0].name + " "); 
      Voter.print(voters[i].name, voters[i].preference); 
     } 
    } 
} 

ループ内では、選択されたインデックスを有権者に更新するのではなく、ループのすべてのインデックスが同じ情報で更新されます。

public class Voter 
{ 
    public static String name; 
    public static String[] preference = new String[5]; 

    public static void print(String name1, String[] preference1) 
    { 
     System.out.print("Voter: name=" + name1 + " preferences:"); 
     for (int i=0; i<5; i++) 
     { 
      System.out.print(" " + preference1[i]); 
     } 
     System.out.println(); 
    } 
} 

だから、有権者の出力[0] .nameのは、それが一度だけ変更されていていても、たびにループを反復処理を変更しています。

答えて

0

変更:

public static String name; 
public static String[] preference = new String[5]; 

へ:

public String name; 
public String[] preference = new String[5]; 
0

あなたのメンバ変数は、それがすべての瞬間にあなたは静的メンバの値を変更したことを意味し、静的であったため。あなたのデザインの適切なクラスのモデルとしてVoterを使用している場合@Pooyaは、前述したように、あなたがいずれかのより良い答えたり、それらを変更する必要があり、私は、

private String name; 
private String[] preference = new String[5]; 

(セッターせずにそれらを変更することはできません)物事をより意味のあるものにするためにコンストラクタ/ゲッター/セッターを使用することをお勧めします。 「Hello World」のスタイルの治療のために、それはおそらく大丈夫だけど良い練習は良い習慣です:

パブリッククラス投票 { プライベート文字列名=「」; プライベートString [] preference =新しいString [5];

// If possible define constructors where you can supply the preference size 

public static void print(String name1, String[] preference1) 
{ 
    System.out.print("Voter: name=" + name1 + " preferences:"); 
    for (int i=0; i<preference1.length; i++) /* don't hardcode the condition, what if you decided to change the preference size to 3 or 4? */ 
    { 
     System.out.print(" " + preference1[i]); 
    } 
    System.out.println(); 
} 

public void setName(String name) { 
    this.name = name; 
} 

public void setPreference(String[] preference) { 
    this.preference = preference; 
} 

// Define the getters (if you know what I mean) 

}

関連する問題