0
import java.util.Scanner;
public class Ideone
{

    public static void main(String[] args) 
    {
        int reader;
        Scanner kBoard = new Scanner(System.in);
        do
        {
            System.out.println("Insert a number of rows: ");

                reader = kBoard.nextInt();
                printDiamond(reader); 


        }while(reader != 0);

    }

    public static void printWORD(int n)
    {
        if(n >= 1)
        {
          System.out.print("SAMPLE");
            printWORD(n - 1);
        }
    }

    public static void printTopTriangle(int rows)
    {
        int x = 1;
        for(int j = (rows - 1); j >= 0; j--,x +=2)
        {
            printSpaces(j);
            printWORD(x);
            System.out.print("\n");
        }
    }

    public static void printSpaces(int n)
    {
        if(n >= 1)
        {
            System.out.print(" ");
            printSpaces(n - 1);
        }
    }

    public static void printBottomTriangle(int rows, int startSpaces)
    {
        int x = 1 + (2*(rows - 1));
        for(int j = startSpaces; j <= (rows) && x > 0; j++,x -=2)
        {
            printSpaces(j);
            printWORD(x);
            System.out.print("\n");
        }
    }
    public static void printBottomTriangle(int rows)
    {
        int x = 1 + (2*(rows - 1));
        for(int j = 0; j <= (rows - 1) && x > 0; j++,x -=2)
        {
            printSpaces(j);
            printWORD(x);
            System.out.print("\n");
        }
    }

    public static void printDiamond(int rows)
    {
        printTopTriangle((int)rows/2 + 1);
        printBottomTriangle((int)rows/2, 1);
    }
}

我的程序应该显示由单词“SAMPLE”组成的菱形。但是当我运行它时,它会显示一个太空船的形状。如何修复此错误,以便打印带有“SAMPLE”字样的完美钻石?

4

3 回答 3

0

由于“SAMPLE”(6 个字符)的大小,您必须缩进System.out.print(" ");(即 6 个空格而不是 1 个)。

可运行的演示:http: //ideone.com/JHTU6C

注意:我没有修复任何其他问题(您可能想在使用请求它之前检查它是否int存在nextInt()

于 2014-12-08T16:09:05.703 回答
0

如果您将“SAMPLE”更改为“*”或任何其他字符,您将获得菱形。你得到一个宇宙飞船的形状,因为你没有在 printSpaces 方法中放置足够的空间。空格数应接近您在 printWORD 方法中打印的字符数。在 printSpaces 方法中放置 5 或 6 个空格,你会得到接近钻石的东西。

于 2014-12-08T16:10:21.643 回答
0

更改这些方法如下:

public static void printTopTriangle(int rows)
   ...
   printSpaces(j*6);



public static void printBottomTriangle(int rows, int startSpaces)
   ...
   printSpaces(j*6);

注:6是常数的长度SAMPLE

于 2014-12-08T16:16:39.270 回答