简体   繁体   中英

How would I add an object with an int and a string value to an array in Java

So far for the class I have:

public class Candidate
 {
// instance variables
private int numVotes;
private String name;

// Constructor for objects of class Candidate
public Candidate(String name, int numVotes)
{
    // initialize instance variables
    this.name = name;
    this.numVotes = numVotes;
}

public String getName()
{
    return name;
}

public int getVotes()
{
    return numVotes;
}

public void setVotes(int n)
{
    numVotes = n;
}

public void setName(String n)
{
    name = n;
}

public String toString()
{
    return name + " received " + numVotes + " votes.";
}
}

I have a tester class where I have an array that I want to add the objects to. The tester class so far is:

 public class ElectionTesterV1
 {
Candidate Candidate[] = new Candidate[5];
 }

So far I have tried

 Candidate[0] =  ("John Smith",5,000);

but I get lost of errors illegal start type and identifier needed. How would I add an object with the same format with a name and then a number into the array. I'm supposed to be using an array, not an arraylist

Your array is Candidate[] , so therefore it needs to hold instances of Candidate . The class Candidate may be instantiated with a String and and int (per the constructor).

Note: I changed the array name to candidates (plural) to help distinguish the usage.

You can add to the array by:

// create the array
Candidate[] candidates = new Candidate[5];

// add the first person
candidates[0] = new Candidate("John Smith", 5000);

So the test class might look like:

public class ElectionTesterV1
{
  // array of Candidate objects called candidates
  Candidate[] candidates = new Candidate[5];
  candidates[0] = new Candidate("John Smith", 5000);
  candidates[1] = new Candidate("Mary Sue", 8765);
   ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM