尝试从文本文件读取时发生NullPointerException

硬币鸟

我正在尝试从文本文件中读取这些名称,但出现错误。这是我的主要方法以及相关方法的相关部分:

public class Prog4
{
int mostVoteCount = 0;
int mostVotes = 0;
int mostVotesIndex = 0;
int fewestVoteCount = 0;
int fewestVotes = 0;
int fewestVotesIndex = 0;



String[] candidateArray;
int[] votesArray;

public static void main(String args[]) throws Exception
{
  //Scanner stdin = new Scanner(System.in);
  Scanner stdin = new Scanner(new File("test.txt"));
  int num_votes, num_candidates, election_num = 1;

  System.out.println("Welcome to Prog4!\n");
  Prog4 p4 = new Prog4();

  while (stdin.hasNextLine())
  {
     System.out.println("Results for election " + election_num);
     p4.read_candidates(stdin, p4.candidateArray);
     p4.read_votes(stdin, p4.votesArray);
     System.out.println("Total votes: " + p4.votesArray.length);



  }

 System.out.println("Done. Normal termination of Prog4.");
}

以及所讨论的方法:

public void read_candidates(Scanner stdin, String candidates[])
{
   int candidateCount = 0;
   candidateCount = (stdin.nextInt());

   for (int i = 0; i < candidateCount; i++)
      candidates[i] = (stdin.next());
}

这是我在“测试”文本文件中使用的测试数据:

4

欧文

杰克

史考特

罗比

15 0 1 1 2 3 1 0 0 0 0 1 2 2 1 1

这是堆栈跟踪吗?

java.lang.NullPointerException

at Prog4.read_candidates(Prog4.java:75)

at Prog4.main(Prog4.java:35)
保罗·里希特

您永远不会实例化您的candidateArrayvotesArray,因此当您将它们传递给read_candidates方法时,它们为null 我猜想它失败了:

candidates[i] = (stdin.next());

您基本上是在尝试使用空对象(candidates在这种情况下对象)做某事在代码中的某些时候,在尝试使用它们之前,您必须执行类似的操作candidateArray= new String[],并且对进行相同的操作votesArray

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章