Write java code to print following diamond patterns. This program must take number of lines from user. If even number is entered than program must ask again user to enter odd number.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int lines;
do {
System.out.print("Enter number of lines(odd): ");
lines = in.nextInt();
} while (lines % 2 == 0);
int stars = 1;
for (int i = 0; i < lines; i++) {
for (int j = 0; j < ((i < lines / 2) ? lines / 2 - i : i - lines / 2); j++) {
System.out.print(" ");
}
for (int j = 0; j < stars; j++) {
System.out.print("*");
}
stars = (i < lines / 2) ? stars + 2 : stars - 2;
System.out.println();
}
}
}
Comments
Leave a comment