如何在另一个类中更新数组的单个索引

时间:2016-03-31 22:10:37

标签: java arrays

我目前正在尝试更新“Voter”类数组中的各个字段,使用数组选民来保存它们。

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);
        }
    }
}

在嵌套的for循环中,循环使用相同的信息更新数组的每个索引,而不是为选民更新选定的索引。

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的输出都会发生变化,即使它只被改变一次。

2 个答案:

答案 0 :(得分:0)

变化:

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

为:

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

答案 1 :(得分:0)

因为您的成员变量是静态的,所以它意味着您在每个时刻静态修改成员值。正如上面提到的@Pooya,您必须将它们更改为答案或更好(不能在没有制定者的情况下修改它们)

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

如果您在设计中使用Voter作为正确的类模型,我建议您使用构造函数/ getter / setter来使事情更有意义。对于&#34; Hello World&#34;风格治疗,它可能还可以,但良好的做法是良好的做法:

公共课选民 {     private String name =&#34;&#34 ;;     private String [] preference = new 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)

}