Nested Looping

mail@pastecode.io avatar
unknown
java
2 years ago
865 B
31
Indexable
Never
import java.util.Arrays;

class Hello {
	public static void main(String[] args) {
		int[] arrys = { 1, 2, 3, 4, 5, 10, 11, 12, 13, 15 };
		System.out.println(Arrays.toString(arrys));
		String text = "";
		for (int i = 0; i < arrys.length; i++) {
			if (i != 0) {
				if (arrys[i - 1] == arrys[i] - 1) {
					if (i == (arrys.length - 1))
						text = text + "-" + arrys[i];
				} else {
					if (String.valueOf(text.charAt(text.length() - 1)) != String.valueOf(i + 1)) {
						text += "-" + arrys[i - 1];
					} else {
						text += "," + arrys[i];
					}
				}
			} else {
				text += String.valueOf(arrys[i]);
			}
		}
		System.out.println("\n");
		System.out.println("Result : " + text);
		System.out.println("\n");

		System.out.println("Bisa gak hasilnya seperti ini :\n" + "1-5, 10-13, 15");
		System.out.println("\n");
		
	}
}