找出有多少个连续数字

时间:2013-03-22 17:19:53

标签: java

我需要找到我的随机数生成器中出现了多少个连续数字,我的程序工作除了连续数字部分。这就是我所拥有的。我尝试了很多东西,但由于某种原因,我无法弄清楚,请帮忙!有1000个数字和500个随机数,然后我找到了最小值和最大值,然后是平均值。现在我需要找出有多少连续数字出来。 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();
}

1 个答案:

答案 0 :(得分:0)

num不能小于零吗? 错误发生在你的if:

(num>=prev)

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

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

编辑

这部分代码:

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

正在丢弃前两个数字。