// sample prelim question (modified)
// another way of looking at the problem

public class rms_alt {

    public static void main(String[] args) {

	// Initialize data:
	TokenReader in = new TokenReader(System.in);
	final int MAX_COUNT = 4; // total # of molecules to process

	/* Side note: $final$ makes MAX_COUNT unassignable after 10 is 
	   assigned. In either case, MAX_COUNT is known as NAMED CONSTANT.
	   If you skipped $final$, you wouldn't use all uppercase to indicate 
	   to another programmer that max_count could be reassigned. */
	
	double sum = 0.0;         // sum of speeds so far
	double squares = 0.0;     // sum of squared speeds so far
	int k = 0;                // # of speeds processed so far

	System.out.print("Enter a molecule speed: ");
	double speed = in.readDouble(); // speed of a molecule

	// Compute sum of speeds and sum of squared speeds:
	
	/* beware of a 1-off error: see how I use MAX_COUNT-1 */
	while( speed >= 0 && k <= MAX_COUNT-1 ) {

	    System.out.print("Old count: "+k+" ");
	    /* since $speed$ was OK, NOW you increment the count. */
	    ++k;	                         // Increment # of speeds
	    
	    System.out.print("New count: "+k+"\n\n");

	    /* process the current info */
	    sum += speed;	                 // Sum speeds
	    squares = squares + speed*speed;	 // Sum squared speeds

	    /* obtain NEXT input */
	    System.out.print("Enter a molecule speed: ");
	    speed = in.readDouble();             // Read next speed

	}

	// Report if zero molecules, or report percent error of Vrms from Vmean
	if (k >= MAX_COUNT) {
	    System.out.println("Didn't process that...");
	    System.out.println("too many speeds entered!");
	}
	if (k==0) 
	    System.out.println("No molecules!");
	else {
	    double Vmean = sum/k;               // mean speed
	    double Vrms = Math.sqrt(squares/k); // rms speed
	    System.out.println("Percent error: " + 
			       Math.abs(100*(Vrms-Vmean)/Vmean));
	}
    }
}

