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 = 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


 *
 ***
 *
4

1 回答 1

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();
    }
}
于 2013-09-29T03:53:45.387 回答