Java练习:使用递归方法打印星号三角形及其倒三角形 [英] Java Exercise: Printing asterisks Triangle and its inverted triangle using recursion method

查看:2609
本文介绍了Java练习:使用递归方法打印星号三角形及其倒三角形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要打印一个三角形及其倒三角形(站在其尖端)。我只打印出三角形。我知道我可以很容易地使用循环,但是我想知道如何使用递归,在我的情况下,我不知道如何打印两个三角形和倒置的一个。谢谢你。

 示例所需的输出:
*
**
***
****
****
***
**
*

我的代码:

  public class Recursion1 {
public static void main(String [] args){
Recursion1 me = new Recursion1();
me.doIt();
}

public void doIt(){
nums(4);
}

public String nums(int counting){
if(计数< = 0){
return;
}

字符串p = nums(计数-1);
p = p +*;
System.out.print(p);
System.out.println();

return p;
}
}

我的结果:

 结果:
*
**
***
****


解决方案

你必须重新考虑问题,这可能是一个可能的解决方案: >

  public class Recursion1 {
private static int endValue;
private static int startValue = 1;

public Recursion1(int endValue){
Recursion1.endValue = endValue;
}

public static void main(String [] args){
Recursion1 me = new Recursion1(4);
me.doIt();
}

public void doIt(){
nums(*);
}

public String nums(String value){
if(startValue == endValue){
System.out.println(value);
} else {
System.out.println(value);
startValue ++;
value = value.concat(*);
nums(value);
value = value.substring(1);
System.out.println(value);
}
返回值;
}}


I need to print a triangle and its inverted triangle (standing on its tip). I manage to print out only the triangle. I know I can easily use for loop but I want to know how to make use recursion and in my case, I don't know how to print the both triangle and the inverted one.Thank you.

Example desired output:
*
**
***
****
****
***
**
*

My code:

public class Recursion1 {
    public static void main(String[] args) {
        Recursion1 me = new Recursion1();
        me.doIt();
    }

    public void doIt() {        
        nums(4);
    }

    public String nums(int counts) {
        if (counts <= 0) {
            return "";
        }   

        String p = nums(counts - 1);
        p = p +"*";
        System.out.print(p);
        System.out.println();

        return p;
    }
}

My result:

Results:
*
**
***
****

解决方案

You have to rethink the problem, this could be a possible solution:

public class Recursion1 {
private static int endValue;
private static int startValue = 1 ;

public Recursion1(int endValue){
    Recursion1.endValue = endValue;
}

public static void main(String[] args) {
    Recursion1 me = new Recursion1(4);
    me.doIt();
}

public void doIt() {        
    nums("*");
}

public String nums(String value) {
    if( startValue == endValue){
        System.out.println(value);
    }else{
        System.out.println(value);
        startValue ++;
        value = value.concat("*");
        nums(value);
        value = value.substring(1);
        System.out.println(value);
    }
    return value;
}}

这篇关于Java练习:使用递归方法打印星号三角形及其倒三角形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆