java 使用方法和循环绘制带有星星的矩形
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26330852/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Drawing a rectangle with stars using methods and loops
提问by stargazer
I have been trying to create a rectangle that looks like this
我一直在尝试创建一个看起来像这样的矩形
*****
* *
*****
or this
或这个
************
* *
************
depending on the number that I input I can't seem to get it right. This is what I have so far
根据我输入的数字,我似乎无法正确输入。这是我到目前为止
import java.util.Scanner;
public class DrawRectangle{
public static void main (String [] args){
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter an integer greater 1 for the length");
int length = keyboard.nextInt();
int rectangle = draw_rectangle(length);
System.out.print(rectangle);
}
public static int draw_rectangle(int m){
for (int star = 2; star <= m; star++){
System.out.print("*");
}
System.out.println("*\f *\f\r\n");
for(int star = 2; star <= m; star++){
System.out.print("*");
}
return (m);
}
}
采纳答案by stargazer
So you are just trying to create a method that prints a rectangle with N length. First off, this method does not need to return an int, it can just be void. At the end of the main method, you are printing rectangle, which is the same value of length.
所以你只是想创建一个方法来打印一个长度为 N 的矩形。首先,这个方法不需要返回一个int,它可以是void。在 main 方法的末尾,您正在打印rectangle,它与length 的值相同。
import java.util.Scanner;
public class DrawRectangle{
public static void main (String [] args){
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter an integer greater 1 for the length");
int length = keyboard.nextInt();
draw_rectangle(length);
System.out.print(length); // This was rectangle but will print out whatever int the user entered
}
public static void draw_rectangle(int m) {
for(int star = 0; star < m; star++) System.out.print("*");
System.out.print("\n*");
for(int space = 0; space < m-2; space++) System.out.print(" ");
System.out.print("*\n");
for(int star = 0; star < m; star++) System.out.print("*");
System.out.println();
}
}
You will take note of changes in the drawing of the rectangle. The first line is of m*
s and the next line contains of 2 of *
and m-2whitespaces. The line following is just like the first. Take note that loops from 0 to m-1will iterate m times. You should send this to Code Reviewfor more helpful tips.
您将注意到矩形绘图的变化。第一行是m*
s,下一行包含 2 个*
和m-2 个空格。下面的行就像第一行。请注意,从0 到 m-1 的循环将迭代 m 次。您应该将此发送给Code Review以获得更多有用的提示。
回答by Zach
Can't figure why you're starting the loops with 2 or what the middle print is trying to do but here's how i'd do it
不知道为什么你用 2 开始循环,或者中间的打印试图做什么,但这是我的方法
for(int i=0;i<m;i++)
{
for(int j=0;j<m;j++)
{
if(i==0 || i==m)
System.out.print("*");
else if(j==0 || j==m)
System.out.print("*");
else
System.out.print(" ");
}
System.out.print("\n");
}