我需要帮助制作一个程序,您允许用户输入一个字符和一个数字,然后在屏幕上输出一个正方形,该正方形由边长等于输入数字的字符组成。
例如用户输入 $ 和 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);
}
最佳答案
关于您的示例,您说您不知道如何去掉框中的字符。 我相信摆脱你不想要的东西的最好方法就是一开始就不要把它放在那里。让我们稍微考虑一下您的问题。
根据您的示例,您想要一个包含一些空格的字符方框,对吗?
这从根本上分为两条不同的线。
这些是两个水平边缘和 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);
有关重复字符串的更多资料,请参阅 here , 和 here用于 Java 中的用户输入。我希望这对您有所帮助。我离开处理尺寸为 r<2
的正方形作为读者的练习。
关于java - 如何使用 for 循环创建一个正方形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20061163/