Исправить исключение NullPointerException? [Дубликат]

1

Как я могу заставить программу выводить всю информацию? В настоящее время IT возвращает ошибку NullPointException. Благодарю. Я должен использовать методы удаления так, как они есть, я не могу их изменить, но я уверен, что я должен что-то сделать.

 public class TestCandidate7
{     

 public static int getTotal(Candidate[] election)
 {
  int total = 0;
  for(Candidate candidate : election )
  {
    total += candidate.numVotes;
  }
   return total;
 }

 public static void printResults(Candidate[] election)
 {
   double percent;
   System.out.println("Candidate        Votes Received      % of Total Votes");
   for (int x = 0; x < election.length; x++)
    {
      percent = (double) (election[x].votes()) / getTotal(election) * 100;
      System.out.printf("%-15s %10d %20.0f", election[x].getName(), election[x].votes(), percent);
      System.out.println();
    }
  }     

   public static void deleteByLoc(Candidate[] election, 
                                int location) 
 {          
   if ((location > 0) && (location < election.length))
      {
          //move items up in the array -
          for(int index = location; index < election.length -1; index++)
              election[index] = election[index + 1];

          election[election.length-1] = null;
      }
}

   public static void deleteByName(Candidate[] election, 
                                String find) 
{
    int location = 0;
    int index;

    // find location of item you want to delete
    for(index = 0; index < election.length; index++)
      if ((election[index] != null) && (election[index].getName().equals(find)))
           { 
               location = index;
               break;
            }
      else if (election[index] == null)
            {
                location = -1;
                break;
            }

   if ((index != election.length) && (location >= 0))       
    { //move items up in the array 
      for(index = location; index < election.length -1; index++)
         election[index] = election[index + 1];

       election[election.length-1] = null;
    }
}  

 public static void main(String[] args)
 {
    Candidate[] election = new Candidate[10];

    // create election
    election[0] = new Candidate("John Smith", 5000);
    election[1] = new Candidate("Mary Miller", 4000);        
    election[2] = new Candidate("Michael Duffy", 6000);
    election[3] = new Candidate("Tim Robinson", 2500);
    election[4] = new Candidate("Joe Ashtony", 1800);  
    election[5] = new Candidate("Mickey Jones", 3000);
    election[6] = new Candidate("Rebecca Morgan", 2000);
    election[7] = new Candidate("Kathleen Turner", 8000);
    election[8] = new Candidate("Tory Parker", 500);
    election[9] = new Candidate("Ashton Davis", 10000);

    System.out.println("Original results:");
    System.out.println();
    printResults(election);
    System.out.println();
    System.out.println("Total of votes in election: " + getTotal(election) );
    System.out.println();

    deleteByLoc(election, 6);
    System.out.println("Deleted location 6:");
    System.out.println();
    printResults(election);
    System.out.println();
    System.out.println("Total of votes in election: " + getTotal(election) );
    System.out.println();

    deleteByName(election, "Kathleen Turner");
    System.out.println("Deleted Kathleen Turner:");
    System.out.println();
    printResults(election);
    System.out.println();
    System.out.println("Total of votes in election: " + getTotal(election) );
    System.out.println();

 }

}

кандидат

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

/**
 * Constructor for objects of class InventoryItem
 */
 public Candidate(String n, int v)
 {
 // initialise instance variables
 name = n;
 numVotes = v;
 }
 public int votes() 
 {
    return numVotes;
 }
 public void setVotes(int num)
 {
    numVotes = num;
 }
 public String getName()
 {
    return name;
 }
 public void setName(String n)
 {
    name = n;
 }    
 public String toString()
 {
   return name + " received " + numVotes + " votes.";
 }

}

  • 2
    Stacktrace, пожалуйста?
  • 0
    Кроме того, предоставьте (соответствующий) код для объекта-кандидата (и любых других пользовательских классов), чтобы мы могли скомпилировать и проверить его для вас ...
Показать ещё 4 комментария
Теги:
nullpointerexception

1 ответ

0

Когда вы "удаляете" элементы массива, после сдвига вы назначаете null самому правому элементу массива.

В getTotal() вы перемещаете весь массив и извлекаете значение numVotes для каждого элемента. Когда вы достигаете null элемента, вы получаете исключение, так как null не имеет полей.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню