-1

我需要找出我的随机数生成器中有多少个连续数字,除了连续数字部分外,我的程序都在工作。这是我得到的。我已经尝试了很多东西,但由于某种原因我无法弄清楚,请帮助!有1000个数字和500个随机数出来,然后我找到最小和最大值,然后取平均值。现在我需要找出 fe 9、10、11 或 55、56、57 有多少个连续数字...我也收到此错误...--线程“main”中的异常 java.util.NoSuchElementException

    int num, largest, smallest, sum = 0, count = 0;
    int programnumber = 6;
    header (prw, programnumber);
    double average = 0;

    Random gen = new Random();
    FileWriter fw = new FileWriter("randomdata.txt");
    for (int i1 = 0; i1 < 500; i1++){
        num = gen.nextInt(1000);
        fw.write(num + "\n");
        count++;

    }
    fw.close();

    File numfile = new File("randomdata.txt");
    Scanner infile = new Scanner(numfile);
    largest = infile.nextInt();
    smallest = infile.nextInt();
    largest = 0;
    smallest = 999;
    while (infile.hasNext()){
        num = infile.nextInt();
        System.out.println(num);
        if (num > largest){
            largest = num;
        }
        if (num < smallest){
            smallest = num;
        }
        sum = sum + num;
        count++;
        }
    average = (double) sum / count;
    System.out.println("The largest is: " + largest);
    prw.println("The largest is: " + largest);
    System.out.println("The smallest is: " + smallest);
    prw.println("The smallest is: " + smallest);
    System.out.println("The average is: " + average);
    prw.println("The average is: " + average);

            // here is the part where I am stuck
    int prev, consec=0;
    prev= infile.nextInt();
    num= infile.nextInt();
    while (num >= 0) { 
        if (num >= prev){  
            consec++; 
            prev = num; 
            num = infile.nextInt();
        }

    }
    System.out.println(consec);








    prw.close();
}
4

1 回答 1

0

不能num小于零吗?错误出现在您的 if 中:

(num>=prev)

并不意味着它们是连续的。只有第一个大于或等于。应该是(num+1==prev)

此外,您正在阅读所有文件以查找最大、最小和平均值,验证连续数字时无需读取任何内容。

编辑

这部分代码:

largest = infile.nextInt();
smallest = infile.nextInt();
largest = 0;
smallest = 999;

正在丢弃前两个数字。

于 2013-03-22T17:27:05.267 回答