【发布时间】:2019-06-13 07:57:52
【问题描述】:
所以我在我的项目中编写了一个代码,我在一个单独的文件中存储了一些行中的投票。然后我读取该文件并将行中的投票提取到一维数组中,然后我必须像用户输入 1 一样增加它们,第一行添加 1 个投票,如果用户输入 2,则增加一个投票到2行以此类推。之后,我必须将该递增的数组与添加的投票存储到最初提取它们的同一文件(覆盖)中。
我面临两个问题,首先,当用户输入 1 时,实际上执行了 7 次增量,因为循环运行了 7 次,因为数组长度为 7。第二个问题是,文件被覆盖后,它显示结果在输出中增加了投票,但文件变为空,当它再次运行时,它显示 0,0,0,0 .... 即使在最后使用 output.close() 之后也是如此。
请建议,我明天要提交项目,还有很多要写的,如果有人可以请借2.3小时帮助也很棒。
public static int[] voteCasting(String resultFile) {
String[] votesArray = new String[7];
int[] votesConverted = new int[votesArray.length];
try {
String partyVotes = "";
int castedVotes;
int i = 0;
Scanner uI = new Scanner(System.in);
Scanner rF = new Scanner (new File(resultFile));
int userInput = uI.nextInt();
while (rF.hasNext()) {
partyVotes = rF.next();
votesArray[i]= partyVotes;
votesConverted[i] = Integer.parseInt(votesArray[i]);
i++;
if (userInput == 1) {
votesConverted[0] = ++votesConverted[0];
}
else if (userInput == 2) {
votesConverted[1] = votesConverted[1]++;
}
else if (userInput == 3) {
votesConverted[2] = votesConverted[2]++;
}
else if (userInput == 4) {
votesConverted[3] = votesConverted[3]++;
}
else if (userInput == 5) {
votesConverted[4] = votesConverted[5]++;
}
else if (userInput == 6) {
votesConverted[6] = votesConverted[6]++;
}
else if (userInput == 7) {
votesConverted[7] = votesConverted[7]++;
}
}
PrintWriter wF = new PrintWriter(resultFile);
while ( rF.hasNext()) {
wF.write(votesConverted[i]);
i++;
}
wF.flush();
wF.close();
} catch (IOException ex) {
Logger.getLogger(ProjectTesting.class.getName()).log(Level.SEVERE, null, ex);
}
return votesConverted;
}
【问题讨论】:
-
为什么你认为第二个
while ( rF.hasNext())会循环播放?你已经用尽了rf的所有token,所以在rF.hasNext()返回false并结束第一个循环之后,你为什么相信它会因为你再次调用它而突然返回true? -
我该怎么办? ....
标签: java arrays file-handling