KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jgroups > tests > CheckMonotonicallyIncreasingNumbers


1 package org.jgroups.tests;
2
3 import java.io.*;
4
5 /**
6  * Checks whether numbers in a stream are monotonically increasing, e.g.
7  * <pre>
8  * 1
9  * 2
10  * 3
11  * 4
12  * </pre>
13  * @author Bela Ban
14  * @version $Id: CheckMonotonicallyIncreasingNumbers.java,v 1.2 2006/01/16 13:01:26 belaban Exp $
15  */

16 public class CheckMonotonicallyIncreasingNumbers {
17
18     static int check(InputStream in) throws IOException {
19         Reader r = new BufferedReader(new InputStreamReader(in));
20         StreamTokenizer st = new StreamTokenizer(r);
21         int i, cnt=0, num=0, tmp, incorrect=0;
22         boolean first_read=false;
23
24         while(true) {
25             i=st.nextToken();
26             if(i == StreamTokenizer.TT_EOF)
27                 break;
28             tmp=(int)st.nval;
29             if(!first_read) {
30                 first_read=true;
31             }
32             else {
33                 if(tmp != num +1) {
34                     System.err.println("Number read: " + tmp + ", previous number: " + num +
35                             " (lineno: " + st.lineno() + ")");
36                     incorrect++;
37                 }
38             }
39             num=tmp;
40             cnt++;
41             if(cnt > 0 && cnt % 1000 == 0)
42                 System.out.println("read " + cnt + " numbers");
43         }
44         return incorrect;
45     }
46
47
48     public static void main(String JavaDoc[] args) throws IOException {
49         String JavaDoc file=null;
50         for(int i=0; i < args.length; i++) {
51             if(args[i].equals("-file")) {
52                 file=args[++i];
53                 continue;
54             }
55             help();
56             return;
57         }
58         FileInputStream fis=new FileInputStream(file);
59         int incorrect=CheckMonotonicallyIncreasingNumbers.check(fis);
60         if(incorrect == 0) {
61             System.out.println("OK, all numbers are monotonically increasing");
62         }
63         else {
64             System.err.println("Failure: there are " + incorrect + " incorrect numbers");
65         }
66         fis.close();
67     }
68
69     private static void help() {
70         System.out.println("CheckMonotonicallyIncreasingNumbers [-help] [-file <filename>]");
71     }
72 }
73
Popular Tags