//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);
}
//having a hard time turning the top around so it starts small then enlarges.
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);
}
/* output
/ \\ \\ / \\ / \\ / \\ / \\ / \\ / \\ / \\ / \\ / */
I worked out a top down solution, not the most fancy bit, but it makes recursive calls, and any professor'd like to see it. The best I can turn in on a Saturday night. The diamond does look a bit dodgy eh, but you can always trim that up the way you like then...
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);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.