University of Toronto - Summer 2001
Department of Computer Science

Week 8 - Loop Example

Loop Example

Write a complete program to read a sequence of strings, stopping when the input string is "XXX". The program's output is the string with the most J's in it. Only upper case J's count. Do not use arrays or Vectors.

Sample input:

   Java
   Jumping jellybeans, said Jim.
   XXX

Sample output:

   Jumping jellybeans, said Jim.

Java program

// Programmer: Andria Hunter
// Date:       July 3, 2001
// Course:     CSC108
//
// JFinder: this class determines which line of input has the most J's
//          in it.  It prints out this line of input.
//
import java.io.*;
class JFinder {

	/**
	* main: This method is where the program starts execution.  It
	* reads input from the user and then prints out the line of
	* input that has the most J's in it.
	*/
	public static void main (String[] args) throws IOException {

		BufferedReader in = new BufferedReader(new InputStreamReader
			(System.in));

		String mostLine = "";		// stores line with most J's so far
		int mostCount = 0;		// largest number of J's in a line so far
		final String STOPPER = "XXX";	// stop when this is entered

		// Each iteration of this loop reads in one line of input from
		// the user, counts the number of J's in it, and keeps track
		// of the line with the most J's so far.
		while (true) {

	 		String line = in.readLine();
	 		if (line.equals(STOPPER)) {
				break;
			}

			// Go through each character in this line, and count
			// how many J's are found.
	 		int count = 0;
	 		for (int i = 0; i < line.length(); i++) {
				if (line.charAt(i) == 'J') {
					count++;
				}
			}

			// This line has more J's than any other lines.
			if (count > mostCount) {
				mostCount = count;
				mostLine = line;
			}
		}

		// Print out the line that has the most J's, or if
		// no line had any J's, print an error message.
		if (mostCount >= 0) {
	 		System.out.println (mostLine);
		} else {
	 		System.out.println ("No input!");
		}
	}
}