java - 递归制作钻石
问题描述
//Making a diamond using recursive methods. The diamond is filled with //whitespace then outlined using / and \.
//Using java, and has to be using recursive methods.
public static void diaTop(int w){ //this is to make top of diamond
if(w == 0 )return;
else System.out.print('/'); //printing left side of diamond
for(int i = 0; i < w; i++){ //for loop to make spaces
System.out.print(" ");
}
System.out.print('\\'); //printing right side of diamond
System.out.println();
diaBot(w-1);
}
//很难把顶部转过来,所以它开始变小然后变大。
public static void diaBot(int w){ //this is to make bottom of diamond
if(w == 0 )return;
else System.out.print('\\');//printing left side of diamond
for(int i = 0; i < w; i++){ //for loop to make spaces
System.out.print(" ");
}
System.out.print('/'); //printing right side of diamond
System.out.println();
diaBot(w-1);
}
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
System.out.println("Input width of diamond: ");
int w = scnr.nextInt(); //getting width of diamond.
diaTop(w);
diaBot(w);
}
/* 输出
/ \ \ / \ / \ / \ / \ / \ / \ / \ / \ / */
解决方案
我制定了一个自上而下的解决方案,不是最花哨的解决方案,但它会进行递归调用,任何教授都希望看到它。我能在周六晚上上交的最好的。钻石看起来确实有点不靠谱,嗯,但是你可以随时按照你喜欢的方式修剪它......
class Diamond {
void draw(int width, int height) {
if (height - width == height) {
return;
} else {
width -= 2;
//this bit right here works out the width of spaces
System.out.print("\n\\");
for (int i = 0; i < width; i++)
System.out.print(" ");
System.out.print("/");
//This calls the whole thing again, right recursion.
draw(width, height);
}
}
void drawTop(int width, int height) {
if (height - width == height) {
return;
} else {
width -= 2;
//This does the same as above but in reverse...
System.out.print("\n/");
for (int i = 0; i <(height - 2) - width ; i++)
System.out.print(" ");
System.out.print("\\");
//The bit is called here, resursion...
drawTop(width, height);
}
}
}
public class Main {
public static void main(String[] args) {
Diamond diamond = new Diamond();
//Its not too fancy here, but its right recursion.
//Go ahead, an add your scanner ere if ya like...
diamond.drawTop(8,8);
diamond.draw(8, 8);
}
}
推荐阅读
- reactjs - 使用 cognito 用户组登录后重定向
- powershell - 我们可以在 PowerShell 中编写明星程序吗?
- python - 尝试加入两个 pandas 数据框但得到“ValueError:您正在尝试合并对象和 int64 列。”?
- ios - 解码为 NSManagedObject 对象后需要获取请求
- php - 在 PHP 中调试 libcurl 本身(低级)
- c++ - 从透视切换到正交保持模型和缩放的相同视图大小
- python - 如何使用 lambda 和 hasattr 过滤嵌套属性上的对象数组?
- mysql - MySQL 和 MariaDB SELECT 返回类型的区别
- javascript - 更快地显示循环元素的 HTML
- jmeter - JMeter“验证脚本” - 我应该在“结果树”中看到什么?