Java的一个读取文件的超简单有关问题,为什么会出错!
阅读
直接上代码:
public class FCADSTREE {
public static void main(String[] args) throws IOException {
File filefca = new File("teamStatis.txt");
Scanner inputfca = new Scanner(filefca);
TEAM[] teams = new TEAM[4];
for (int i = 0; i < 1; i++) {
teams[i].name = inputfca.next();////这行报错!!!
teams[i].attack = inputfca.nextInt();
teams[i].control = inputfca.nextInt();
teams[i].defend = inputfca.nextInt();
}
inputfca.close();
for (int i = 0; i < 1; i++)
System.out.println(省略了);
}
}
TEAM类为:
public class TEAM {
String name=new String();
int attack;
int control;
int defend;
}
报错信息为:java.lang.NullPointerException
teamStatis.txt这个文件肯定没有问题,因为如果我用
String string=inputfca.next();
则可以正常读取。
请问程序错在哪里了??
------解决思路----------------------
TEAM[] teams = new TEAM[4];
for (int i = 0; i < 1; i++) {
teams[i].name = inputfca.next();////这行报错!!!
teams[i].attack = inputfca.nextInt();
teams[i].control = inputfca.nextInt();
teams[i].defend = inputfca.nextInt();
}
这样写,TEAM[i] 肯定是null,然后null.name 可想而知, 自己debug一下
------解决思路----------------------
TEAM[] teams = new TEAM[4]; 只是定义了一个类别数组,但是内容还没有写呢,你就直接调用了。先去初始化
------解决思路----------------------
在for循环里在加一句teams [i]=new TEAM();
阅读
上一篇:请问一个关于垃圾回收不彻底的有关问题 下一篇:返回列表