带有输入的Java中的Diamond(使用嵌套for循环或一些条件if语句)

时间:2013-09-29 03:01:53

标签: java loops for-loop

我必须要求输入并显示有许多线条的钻石。我有一个代码,但它显示的行数少于我输入的数量。我对哪里出错了感到困惑?

这是我目前的代码:

代码:

import java.util.Scanner;

public class PROBLEM3 {

    public static void main(String [] args){

        Scanner scan = new Scanner (System.in);

        System.out.println("Please input number of lines:");
        int i = 0, j, k, n;
        n = scan.nextInt();


        for(k = 0; k <= n / 2; k++){
            for (i = 0; i <  n - k; i++){
                System.out.print(" ");
            }
            for (j = 1; j < k; j++){
                System.out.print("*");
            }
            for (j = 1; j < k - 1 ; j++){
                System.out.print("*");
            }

            System.out.println("");
        }

        for (k = (n / 2); k <= n ; k++){
            for (i = 0; i < k; i++){
                System.out.print(" ");
            }
            for ( i = 1; i < n - k ; i++){
                System.out.print("*");
            }
            for (j = 0; j < n - k - 2; j++){
                System.out.print("*");
            }

            System.out.print("\n");
        }

        scan.close();
    }
}

输出:

 Please input number of lines:
 5


 *
 ***
 *

1 个答案:

答案 0 :(得分:0)

请尝试以下代码,

import java.util.Scanner;

public class PROBLEM3 {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.println("Please input number of lines:");
        int i = 0, j, k, n;
        n = scan.nextInt();

        for (k = 1; k <= (n + 1) / 2; k++) {
            for (i = 0; i < n - k; i++) {
                System.out.print(" ");
            }
            for (j = 0; j < k; j++) {
                System.out.print("* ");
            }
            System.out.println("");
        }

        for (k = ((n + 1) / 2); k < n; k++) {
            for (i = 1; i < k; i++) {
                System.out.print(" ");
            }
            for (j = 0; j < n - k; j++) {
                System.out.print(" *");
            }
            System.out.println("");
        }

        scan.close();
    }
}