我正在尝试创建一个程序,该程序可以使文件随机生成数字,并且希望该程序从文件中读取这些数字并进行分析。如果随机生成的数字不等于0,则程序应继续生成数字,但如果确实等于0,则程序将停止。但是,看来我的程序没有读取这些数字。
我尝试将outFile.close();
和inFile.close();
放在几个不同的地方,以查看是否可以解决任何问题,但似乎没有解决问题。我尝试用笔和纸来跟踪代码,但找不到任何错误。也许可能是我放置的outFile.close();
和inFile.close();
,但是我找不到任何错误。
import java.util.*;
import java.io.*;
public class squirrel {
public static void main(String[] args) throws IOException{
Scanner in = new Scanner(System.in);
PrintWriter outFile = new PrintWriter(new File("squirrel.txt"));
Scanner inFile = new Scanner(new File("squirrel.txt"));
Random rand = new Random();
int squirrelNum;
int foxSquirrel = 0;
int squirrelsSeen = 0;
int trials = 0;
System.out.println("Welcome to the Fox Squirrel Simulator\n");
System.out.println("How many trials should be simulated?");
System.out.println("Enter a value greater than 1000: ");
trials = in.nextInt();
while(trials <= 1000)
{
System.out.println("Please try again. Enter a value greater than 1000: ");
trials = in.nextInt();
}
for(int i = 0; i <= trials; i ++)
{
squirrelNum = rand.nextInt(10);
outFile.println(squirrelNum);
while(inFile.hasNextInt())
{
int token = inFile.nextInt();
while(token != 0)
{
squirrelsSeen ++;
}
if(token == 0)
{
foxSquirrel ++;
squirrelsSeen ++;
}
outFile.close();
}
System.out.println("squirrelsSeen: " + squirrelsSeen);
System.out.println("foxSquirrel: " + foxSquirrel);
}
inFile.close();
System.out.println("\nsimulating trials now... one moment please...\n");
System.out.println("The results!");
System.out.println("The average number of squirrels until spotting a Fox Squirrel at the city park is: " + (((double)foxSquirrel / squirrelsSeen) * 100));
}
}
答案 0 :(得分:2)
这是使用扫描仪完成的过程。
File file = new File("squirrel.txt");
try {
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
int i = sc.nextInt();
System.out.println(i);
}
sc.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
就像你说的那样。您将.close()放入代码的while循环中。尝试将其放在外面。
答案 1 :(得分:2)
new PrintWriter(new File("squirrel.txt"))
立即删除文件。来自documentation:
如果文件存在,则它将被截断为零大小;否则,将创建一个新文件。
不可能同时读取和写入同一文件。 (实际上,在某些情况下是有可能的,但在这里并不适用。)
在完成从文件读取并调用inFile.close()
之前,请勿创建PrintWriter。或者,写一个不同的文件,完成后重命名它以匹配原始文件。