Share on Google+Share on Google+

Display String in Circular Format in Java

Advertisement
In this section, you will learn how to display string in a circular format.

Display String in Circular Format in Java

In this section, you will learn how to display string in a circular format.For this, we have specified the string 'WORD'. Now we have to shift each character of the string in the circular format. So we have created following method that will shift each character to left in a circular way:

public static void shiftLeft(String[] array, int amount) {
		for (int j = 0; j < amount; j++) {
			String a = array[0];
			int i;
			for (i = 0; i < array.length - 1; i++)
				array[i] = array[i + 1];
			array[i] = a;
		}
	}

Here is the code:

public class CircularFormat {
	public static void shiftLeft(String[] array, int amount) {
		for (int j = 0; j < amount; j++) {
			String a = array[0];
			int i;
			for (i = 0; i < array.length - 1; i++)
				array[i] = array[i + 1];
			array[i] = a;
		}
	}

	public static void printArray(String[] array) {
		for (int x = 0; x < array.length; x++) {
			System.out.print(array[x]);
		}
	}

	public static void main(String[] args) {
		String st = "WORD";
		String array[] = st.split("");
		int len = array.length;
		shiftLeft(array, 2);
		printArray(array);
		System.out.println(" ");
		shiftLeft(array, 2);
		printArray(array);
		System.out.println(" ");
		shiftLeft(array, 2);
		printArray(array);
		System.out.println(" ");
		shiftLeft(array, 2);
		printArray(array);
	}
}

Output:

ORDW
DWOR
WORD
RDWO

Advertisements

Advertisement

Posted on: February 13, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.