Simple Label Tutorial

A simple example of using labels within Java. The method below will determine whether one String is a substring of another without using Java's built-in String.contains(String) method. Mostly to demonstrate how to use labels.

ContainsSubString.java

Another very simple example of using labels within Java. The user is prompted to input the number 1 followed by the number 2, with a line break after each. If the user incorrectly inputs either value, they will have to start over.

JumpTable.java

package edu.rutgers.sakai.java.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * A simple example of using labels within Java. Inspired by a question by Yunku
 * Jang.
 * 
 * @author Robert Moore
 * 
 */
public class JumpTable {
	
	/**
	 * A very simple example of label usage in Java.
	 * @param args ignored
	 */
	public static void main(String[] args) {

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

		int userSelection1 = Integer.MIN_VALUE;
		int userSelection2 = Integer.MIN_VALUE;
		do {
			doubleInput: {
				// Get the first input
				System.out
						.println("Please enter the number 1 and press <Enter>:");
				userSelection1 = getInputInteger(in);

				if (userSelection1 != 1) {
					break doubleInput;
				}

				// Now for the second input
				System.out
						.println("Please enter the number 2 and press <Enter>:");
				userSelection2 = getInputInteger(in);
			} // break doubleInput; will jump to here
		} while (userSelection1 != 1 || userSelection2 != 2);

		System.out.println("You followed the directions! Congratulations!");
	}

	/**
	 * Reads an integer from the {@code BufferedReader}, returning the integer
	 * or {@link Integer#MIN_VALUE} if an exception occurs.
	 * 
	 * @param r
	 *            the input to read from.
	 * @return the integer read from the {@code BufferedReader}, or
	 *         {@code Integer.MIN_VALUE} if an exception occurs.
	 */
	public static int getInputInteger(BufferedReader r) {
		try {
			String userInput = r.readLine();
			return Integer.parseInt(userInput);
		} catch (Exception e) {
			e.printStackTrace();
			return Integer.MIN_VALUE;
		}
	}
}