大神给,写个java递归题

tonyhit0707 2013-04-18 08:56:12
编写一个能产生下面所示输出的方法.这个输出是通过调用数字1写出的.在这个铺子中,停止于第4级,但你的方法应该能继续到任何特定的一级.
This was written by call nuumber 2.
This was written by call nuumber 3.
This was written by call nuumber 4.
This ALSO was written by call nuumber 4.
This ALSO was written by call nuumber 3.
This ALSO was written by call nuumber 2.
This ALSO was written by call nuumber 1.
...全文
213 6 打赏 收藏 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
WingSa 2013-04-22
  • 打赏
  • 举报
回复
重新看了一下输出,忽略了以下方面: 1、原输出共7行,而我的代码只有6行 2、内容上,原输出第4行已经与前面3行不一样了 修改后代码如下,测试输出效果与原输出一致(如果你的输出中,第1行没有空格,可以将if块中的j和else块中的i的起始值都改为1;有空格的话,以下代码就满足所要求的输出了):
package test;
 
public class CirculateTest {
    public static void sob(int start, int end) {
        if (start == end + 1) {
            for (int i = end + 1; i > 0; i--) {
                for (int j = 0; j < i; j++) {
                    System.out.print(" ");
                }
                System.out.println("This ALSO was written by call number " + i
                        + ".");
            }
        } else {
            for (int i = 0; i < start; i++){
                System.out.print(" ");
            }               
            start++;
            System.out.println("This was written by call number " + start + ".");
 
            sob(start, end);
        }
    }
 
    public static void main(String[] args) {
        CirculateTest.sob(1, 3);
    }
}
tonyhit0707 2013-04-18
  • 打赏
  • 举报
回复
感谢3楼,你的代码基本是对的,输出有些小问题,就是for (int j = 0; j < i; j++) { System.out.print(" ");这个j的初始值应该是1
傲世孤尘 2013-04-18
  • 打赏
  • 举报
回复
帮你顶一下,顺便捡点分
WingSa 2013-04-18
  • 打赏
  • 举报
回复
2楼没有考虑空格数量的变化,更改后的代码见上楼
WingSa 2013-04-18
  • 打赏
  • 举报
回复
package test;

public class Test {
	public static void sob(int start, int end) {
		if (start == end + 1) {
			for (int i = end; i > 0; i--) {
				for (int j = 0; j < i; j++) {
					System.out.print(" ");
				}
				System.out.println("This ALSO was written by call number " + i
						+ ".");
			}
		} else {
			for (int i = 0; i < start; i++)
				System.out.print(" ");
			System.out.println("This was written by call number " + start + ".");
			start++;
			sob(start, end);
		}
	}

	public static void main(String[] args) {
		Test.sob(1, 3);
	}
}
soft_friend 2013-04-18
  • 打赏
  • 举报
回复
public void sob(int start ,int end ){ if(start==end+1){ for (int i = end; i>0; i--) System.out.println ("This ALSO was written by call nuumber "+i+"."); } else { System.out.println ("This was written by call nuumber"+start+"."); start++; sob(start,end); } } 可以实现你的要求,就不知道是不是你要问的

62,620

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧