java 控制台输出菱
在群里看到了一个这样的题目
思路
了解菱形如何画出,我是用的是画上半边,之后画下半边
寻找菱形的规律 使用递归得到上半边为x时,菱形的个数
通过输入的和while循环的菱形个数对比,得到递归了几次,此时递归的次数就是上半层的层数
得到上班层层数,就可以画菱形了
public class tttttttttest {
private static int x = 0;
public static void main(String[] args) throws MalformedURLException, IOException {
Scanner input = new Scanner(System.in);
System.out.println("请输入数字");
int str = input.nextInt();
JSONObject json = bb(str);
int up = json.getIntValue("up");
System.out.println("剩余的*:" + json.getIntValue("remainder"));
for (int i = 0; i <= up; i++) {
for (int j = 0; j < up - i; j++) {
System.out.print(" ");
}
for (int k = 1; k <= 2 * i - 1; k++) {
System.out.print("*");
}
System.out.println();
}
for (int i = up - 1; i > 0; i--) {
for (int j = 0; j < up - i; j++) {
System.out.print(" ");
}
for (int k = 1; k <= 2 * i - 1; k++) {
System.out.print("*");
}
System.out.println();
}
}
public static JSONObject bb(int str) {
int count = 1;
JSONObject json = new JSONObject();
while (true) {
int c = f(count);
if (c > str) {
json.put("remainder", str - f(count - 1)); // 多余的
json.put("up", count - 1); // 上半层
return json;
}
count++;
}
}
public static Integer f(int o) {
if (o == 1) {
return 1;
}
return f(o - 1) + 4 * (o - 1);
}