JAVAlang.NullPointerException即使在获得正确的结果之后也是如此
import java.util.*;
public class Solution5 {
public static void main(String args[])
{
int voterId;
String voterName;
int voterAge;
boolean isVoteCasted;
String constituency;
Scanner sc = new Scanner(System.in);
Vote v[] = new Vote[4];
for(int i=0;i<4;i++)
{
voterId = sc.nextInt(); sc.nextLine();
voterName = sc.nextLine();
voterAge = sc.nextInt();
isVoteCasted = sc.nextBoolean(); sc.nextLine();
constituency = sc.nextLine();
v[i] = new Vote(voterId, voterName, voterAge, isVoteCasted, constituency);
}
String con = sc.nextLine();
sc.close();
int total = findTotalVotesCastedByConstituency(v, con);
if(total == 0)
System.out.println("No votes casted");
else
System.out.println(total);
Vote[] search = searchVoteByAge(v);
if(search == null)
System.out.println("No such voters");
else
{
for(int i=0;i<search.length;i++)
System.out.println(search[i].getVoterId());
}
}
public static int findTotalVotesCastedByConstituency(Vote v[], String con)
{
int c=0;
for(int i=0;i<4;i++)
{
if(con.equalsIgnoreCase(v[i].getConstituency()))
{
if(v[i].getIsVoteCasted())
c++;
}
}
return c;
}
public static Vote[] searchVoteByAge(Vote v[])
{
Vote temp[] = new Vote[4];
Vote t;
int c=0;
for(int i=0;i<4;i++)
{
if(v[i].getVoterAge()<30)
temp[c++]=v[i];
}
//for(int i=0;i<c;i++)
// System.out.println(temp[i].getVoterAge());
if(c==0)
return null;
for(int i=0;i<c;i++)
{
for(int j=0;j<c-i-1;j++)
{
if(temp[j].getVoterAge() > temp[j+1].getVoterAge())
{
t = temp[j];
temp[j] = temp[j+1];
temp[j+1] = t;
}
}
}
return temp;
}
}
class Vote
{
private int voterId;
private String voterName;
private int voterAge;
private boolean isVoteCasted;
private String constituency;
public Vote(int voterId, String voterName, int voterAge, boolean isVoteCasted, String constituency)
{
this.voterId = voterId;
this.voterName = voterName;
this.voterAge = voterAge;
this.isVoteCasted = isVoteCasted;
this.constituency = constituency;
}
public int getVoterId()
{
return voterId;
}
public String getVoterName()
{
return voterName;
}
public int getVoterAge()
{
return voterAge;
}
public boolean getIsVoteCasted()
{
return isVoteCasted;
}
public String getConstituency()
{
return constituency;
}
}
在这段代码中,我试图返回年龄小于30岁的投票者的数组对象(按升序)。 因为我对这个概念还不熟悉,所以我没有使用列表和集合。而是选择了简单的冒泡排序
显示的结果完全正确。我仍然得到一个额外的行,上面写着:Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Vote.getVoterId()" because "search[i]" is null at Solution5.main(Solution5.java:40)
# 1 楼答案
修复大小数组中的问题:
Vote temp[] = new Vote[4];
创建一个具有4个空值的数组。然后用来自
v[]
的值填充这个数组,但是如果没有足够的值来填充整个temp[]
,它的一些位置仍然是null
,所以最后在第40行调用null.getVoterId();
# 2 楼答案
我认为这是你的问题:
当投票者的年龄大于29岁时,temp[c++]将存储null。 另外,是否有任何原因使您将temp初始化为只有4个位置
一个可能的解决方案是:
# 3 楼答案
问题来自:
数组具有固定的大小,如果数组中的对象没有值,将添加
null
(对于基本体boolean=false,int=0…)解决方案
null
检查search[i]
或temp
李>