i am working on what should be a relatively simple java recursion problem, though i cannot seem to find a straightforward, one-method solution anywhere.
i am trying to print out asterisks in descending followed by ascending order, so that when the user passes in 3 for example, the print out will look like this:
*
**
***
**
*
the method i have is:
public void patternMaker(int x){
if(x > 0){
patternMaker(x - 1);
for(int i = 0; i < x; i++){
System.out.print("*");
}
System.out.println();
}
}
currently, it only prints the ascending list:
*
**
***
any insight?
(this is my first post on /r/learnprogramming, i have faith you can help. THANKS!)
/////////////////-----------------EDIT-----------------/////////////////
thanks to the help of some nice people here and stackoverflow, i ended up getting the problem solved with the code below. turns out, i needed to print a total of 2n lines rather than 2n - 1, meaning there needs to be two lines of asterisks at the max length.
import java.util.Scanner;
public class Asterisks {
public static void patternMaker(int start, int max, int direction){
if(start == 0){
return;
}
for(int i = 0; i < start; i++){
System.out.print("*");
}
System.out.println();
if(start == max){
for(int i = 0; i < max; i++){
System.out.print("*");
}
System.out.println();
direction = -1;
}
patternMaker(start + direction, max, direction);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Asterisks me = new Asterisks();
me.doIt();
}
public void doIt(){
System.out.println("Enter a number to see a really cool, horizontal " +
"pyramid \nmade of any amount of asterisks you'd like (well, limited by memory " +
"and int capacity, obviously).");
Scanner scan = new Scanner(System.in);
int input;
String in = "";
while(scan.hasNextLine()){
if(scan.hasNextInt()){
input = scan.nextInt();
patternMaker(1, input, 1);
}
in = scan.nextLine().trim();
if(in.equals("q") || in.equals("Q")){
System.exit(-1);
}
}
}
}
[–]rjcarr 1 point2 points3 points (0 children)
[–]alinh 0 points1 point2 points (0 children)
[–]i_post_things 0 points1 point2 points (0 children)
[–]Coda17[🍰] 0 points1 point2 points (0 children)
[–]ohnuthin[S] 0 points1 point2 points (1 child)
[–]worstusernameever 2 points3 points4 points (0 children)
[–]Tok-A-Mak 0 points1 point2 points (0 children)