java初学者的沙漏示例

时间:2015-09-23 16:54:48

标签: java

我是一名java初学者,只学习了扫描器类,JOptionPane,循环和if语句。

我必须创建一个java程序,根据用户输入的数字打印小时玻璃形状。用户还将给出一个字符符号,该符号是沙漏形状所包含的。例如,如果用户为形状输入“4”而对于字符输入“7”,则它将显示如下:

现在第一个8号“7”。第二行6号“7”。第三行有4个数字“7”。第四行2号“7”。第五行有4个数字“7”。第7行6号“7”。八行8号“7”。

下面是对此的直观表示。

77777777
777777
7777
77
7777
777777
77777777

我给出的唯一指示是:<​​/ p>

要读取字符,请使用以下代码,其中scanner是扫描程序对象:

char symbol = scanner.next().charAt(0);

如果有人可以指出要使用的代码的大致方向,我将不胜感激。

1 个答案:

答案 0 :(得分:0)

以下是我使用您的规范并将评论与您的​​示例相关联的解决方案。

import java.util.Scanner;

class Hourglass
{
    public static void main(String[] args)
    {
        // construct scanner
        Scanner scanner = new Scanner(System.in);
        // get the values for the character and the size of the hourglass from the user
        System.out.print("Enter a symbol: ");
        char symbol = scanner.next().charAt(0);
        System.out.print("Enter the size: ");
        int size = scanner.nextInt();
        // call method to output the hourglass with the user's input
        hourGlass(symbol, size);                
    }

    static void hourGlass(char symbol, int size)
    {
        for (int i = 0; i < size; i++) // loops size times to get the first half + the middle
        {
            // needs to loop 8,6,4,and 2 times; decreases by 2, hence the 2* and -i from outer loop; 
            // I used 0 for the outer loop so 2*(size - 0) = 2 * size to start the top line;
            for (int j = 1; j <= 2 * (size - i); j++)
            {
                System.out.print(symbol);
            }
            System.out.println();
        }
        for (int i = 0; i < size - 1; i++) // loops 1 less than size times to get the bottom
        {
            // loop for 4,6,and 8 times; increases by 2 so 2 * i will control this; starts at size so size + (2 * i) = size + (2 * 0) = size
            for (int j = 1; j <= size + (2 * i); j++)
            {
                System.out.print(symbol);
            }
            System.out.println();
        }
    }
}