这是我项目的开始:
//class variables
private static int numberOfCouples;
//object arrays
private static Witch[] witch;
private static Wizard[] wizard;
//ranking arrays
private static int[][] witchPartnerRanking;
private static int[][] wizardPartnerRanking;
//proposal array
private static boolean[][] proposal;
//DO NOT ALTER THE MAIN METHOD
public static void main(String[] args) throws FileNotFoundException {
go( "coven_dance.txt" );
System.out.println( "Witch array:" );
for ( int i = 0; i < witch.length; i++ ) {
System.out.printf( "Witch %d:, name: %-20s, current partner id: %2d, proposals made: %d%n",
witch[ i ].getId(), witch[ i ].getName(), witch[ i ].getParnerWizardId(), witch[ i ].getNumberOfProposals() );
NullPointerException发生在最后一行。即使我有这个:
private static void go( String fileName ) throws FileNotFoundException {
//1. READ THE FILE
Scanner inStream = new Scanner( new File ( fileName ));
numberOfCouples = inStream.nextInt();
// System.out.println(howManyCouples);
//System.out.print(
inStream.nextLine();
//2. CREATE AND POPULATE THE witch ARRAY
/*Witch[]*/ witch = new Witch[numberOfCouples*2];
/*int [][]*/ witchPartnerRanking = new int[numberOfCouples*2][numberOfCouples];
for (int i = 0; i < numberOfCouples*2; i++) {
if(inStream.hasNextInt()){
//4. CREATE AND POPULATE THE witchPartnerRanking ARRAY
int j = 0;
while(inStream.hasNextInt() && j<numberOfCouples){
int prefer = inStream.nextInt();
//System.out.println(prefer);
witchPartnerRanking[i][j] = prefer;
j++;
}
String bob = inStream.nextLine();
//System.out.println(bob);
}
else{
String name = inStream.next();
//System.out.println(name);
Witch the = new Witch(i, name);
witch[i] = the;
}
}
我不确定发生了什么。如果有人可以提供帮助,那就太棒了。
如果您需要,这是我正在阅读的文件:
4
NannyOgg 0 2 3 1
TiffanyAching 3 2 0 1
MagratGarlick 0 3 2 1
GrannyWeatherwax 0 3 2 1
TheLibrarian 2 1 3 0
PonderStibbons 2 1 3 0
LordVetinari 1 2 0 3
DEATH 3 2 1 0
答案 0 :(得分:0)
您正在访问witch
数组而未进行初始化。
您已声明但未初始化的private static Witch[] witch;
您需要初始化它。一种方法是:
private static Witch[] witch = new Witch[10]; // replace 10 with any array size you want
在Java中,数组被视为常规对象。每当您访问null
的对象时,您都会获得NullPointerException
。