0

在 while 循环中发现困难。我不确定如何开始调用和/或读取生成文件中的每个数字,以便确定最小和最大数字以及总和。另外,如果可能的话,有人可以解释如何编写代码,以便如果任何数字是连续的,它就会计算多少次。

PrintWriter prw = new PrintWriter("results.txt");
int num, largest, smallest, total = 0, count = 0;
int programnumber = 6;
    double average = 0;

PrintWriter prw1= new PrintWriter(new FileWriter("randomdata.txt"));
Random generator = new Random(); 
for (int i = 0; i < 1001; i++){     
         num = generator.nextInt(500);      //Will this generate a file w/ 500 num?
         prw1.write(num + "\n");
    }
    prw1.close();

    largest = 0;        
    smallest = 9999;        
    while (prw1.nextInt()){            //what call statement do I use? 
            num = (prw1.nextInt());    //unsure how to begin reading numbers
            if (num > largest){
                largest = num;
            }
            if (num < smallest){
                smallest = num;
            }
    total += num;
    count++; 
        }
    average = (total / total);
4

2 回答 2

1
num = generator.nextInt(500);      //Will this generate a file w/ 500 num?

上面所做的是生成一个介于 0 和 499 之间的随机值

为了让您从文件中读取,您必须使用,BufferedReader或任何其他阅读器并且不要使用,因为它用于写入而不是读取。ScannerFileReaderPrintWriter

所以你可以试试这个。首先创建一个阅读器:

Scanner scr = new Scanner(fileToRead); //fileToRead should be the file you wrote

然后替换以下内容:

while (prw1.nextInt()){            //what call statement do I use? 
    num = (prw1.nextInt());    //unsure how to begin reading numbers
    // ...
}

有了这个:

while(scr.hasNextLine()){
    num = Integer.parseInt(scr.nextLine());
    // ...
}
于 2013-03-23T00:10:18.573 回答
1

我不认为nextInt你认为它会做。你写:

num = generator.nextInt(500); //Will this generate a file w/ 500 num?

这个问题的答案是否定的。根据文档_Random

public int nextInt(int n)  

返回一个伪随机、均匀分布的 int 值,介于 0(包括)和指定值(不包括)之间,取自该随机数生成器的序列。

因此nextInt(500)生成一个介于 0 和 499(含)之间的数字。

相反,您将希望使用nextInt(1000 + 1)0 到 1000(包括 0 到 1000)来获取数字。

您还应该更改阅读代码。您正在尝试从输出流中读取,这是您无法做到的。您可以更改代码以使用扫描仪,但我个人会使用BufferedReader

try {
    BufferedReader br = new BufferedReader(new FileReader("randomdata.txt"));
    String line = br.readLine();
    while (line != null) {
        // Do something, e.g. Integer.parseInt(line);
        line = br.readLine();
    }
    br.close();
} catch (IOException ie) {
    ie.printStackTrace();
}

BufferedReader使用not 的一个原因Scanner是它可以扩展到不同格式的数据。也许在一行中的每个数字之前都有一个前缀,或者一行中有两个数字。您可以使用BufferedReader抓取整行,然后在解析之前格式化字符串。使用,对onScanner的调用不会很好。nextInt"Number: 6"

于 2013-03-23T00:10:20.780 回答