【问题标题】:how to create a square using for loops如何使用 for 循环创建正方形
【发布时间】:2013-12-02 09:25:39
【问题描述】:

我需要帮助制作一个程序,允许用户输入一个字符和一个数字,然后在屏幕上输出一个正方形,该正方形由边与输入的数字相等的字符组成。

例如用户输入 $ 和 5 - 并输出

            $$$$$
            $   $
            $   $
            $   $
            $$$$$    

到目前为止我试过这个,但我不知道如何摆脱盒子里的字符。

int r,c;
System.out.println (" Please enter the number of rows for the rectangle.");
r=sc.nextInt();
System.out.println (" Please enter a character for the rectangle.");
c=sc.nextInt();
for (int x=r;x>=1;--x) {
    for (int y=r;y>=1;y--) {
        System.out.print (c);
    }
    System.out.println (c);
}

【问题讨论】:

  • 要求代码的问题必须表明对所解决问题的最低理解。 包括尝试过的解决方案、它们为什么不起作用以及预期的结果。请参阅Stack Overflow question checklist
  • 请发布您使用的语言。

标签: java algorithm text for-loop


【解决方案1】:
char c = '$';
int n = 5;

for (int i=0,m=n+1; i<m*n; ++i) {
    putchar(i%m==n?'\n':(i+m)%(m*n)<2*m?c:(i+m+2)%m<3?c:' ');
}

【讨论】:

    【解决方案2】:

    您谈到您的示例时说您不知道如何摆脱框中的字符。 我相信摆脱你不想要的东西的最好方法是一开始就不把它放在那里。让我们考虑一下您的问题。

    根据您的示例,您想要一个包含一些空格的方形字符框,对吗? 这从根本上分为两条不同的路线。 这是两个水平边缘和r-2 垂直边缘。

    我们可以由此构建一个简单的算法。

    Scanner s = new Scanner(System.in);
    int r;
    String c;
    String h, v;
    
    // Get input from the user.
    System.out.println("Please enter the number of rows for the rectangle.");
    r = s.nextInt();
    System.out.println("Please enter a character for the rectangle.");
    c = s.next();
    
    // Make the box's lines.
    h =     new String(new char[r  ]).replace("\0",  c);
    v = c + new String(new char[r-2]).replace("\0", " ") + c;
    
    System.out.println(h);
    for (int i=r-2; i>=1; --i) {
        System.out.println(v);
    }
    System.out.println(h);
    

    有关重复字符串的更多资料,请参阅herehere 以了解 Java 中的用户输入。我希望这对您有所帮助。我将处理大小为r&lt;2 的正方形留给读者作为练习。

    【讨论】:

    • 谢谢我明白了,但是你现在如何让用户输入他们选择的字符和正方形的尺寸?
    • @user3006901:你需要使用类似Scanner的东西。我建议阅读上面的tutorial。我已经编辑了我的答案,以反映它如何用于您的情况。
    猜你喜欢
    • 2012-07-09
    • 1970-01-01
    • 2019-04-09
    • 2021-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多