Skip to main content
5 of 8
deleted 14 characters in body
Jamal
  • 34.9k
  • 13
  • 133
  • 237

Exceptions to control data read flow

I previously posted a Reservoir-Sampling program, which was basically a test version of this one. This is an assignment. In the code below, I use RunTimeException to control when scanner finishes reading data. Reasons for this being:

  1. I cannot use any other library than java.lang.
  2. I cannot use Scanner, either. We have been provided a StdIn class which has a static scanner.next() method only for reading strings.

Note: All the code is inside main() because that is how the API demands it.

Can someone review my code, and possibly tell if there's some way I can improve this?

Edited code:

public class Subset {
    
    public static void main(String[] args) {
        
        int sampleSize = Integer.parseInt(args[0]);
        String[] sample = new String[sampleSize];
        int i = 0;
        // initialize the sample from reservoir
        while(i < sample.length){
            sample[i++] = StdIn.readString(); // StdIn : a class in the provided JAR.
        }
        try{
            for(; ; i++){ 
                int randomIndex = (int)(Math.random()*(i + 1));
                if(randomIndex < sampleSize){
                    sample[randomIndex] = StdIn.readString();
                }
            }
        }catch(RuntimeException e){
            // do nothing
        }       
        for(String s : sample){
            System.out.print(s + " ");
        }
        
    }
}

StdIn.readString():

public static String readString() {
    return scanner.next();
}

Command line input: echo A B C D E F G H I J | java Subset 3
Output: A F C

Somjit Nag
  • 185
  • 1
  • 8