Answer to Question #191541 in Java | JSP | JSF for Hamza

Question #191541

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.


1
Expert's answer
2021-05-12T23:46:11-0400
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();
        }
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS