三角递归Java [英] Triangle Recursion Java
问题描述
在命令行上输入两个数字m和n,并写出一个星号的三角形模式
public class Triangle {
public static void main(String [] args){
int a = 0;
int b = 0;
if(args.length!= 0){
a = Integer.parseInt(args [0]);
b = Integer.parseInt(args [1]);
}
printFirstHalf(a,b);
printSecondHalf(a,b);
public static void printFirstHalf(int m,int n){
if(m == 0){
return;
//递归步骤
for(int i = m; i <= n; i ++){
System.out.print(*) ;
}
System.out.println();
printFirstHalf(m-1,n);
$ b $ public static void printSecondHalf(int m,int n){
if(m == 0){
return ;
}
printSecondHalf(m-1,n);
//递归步骤
(int i = m; i< = n; i ++){
System.out.print(*);
}
System.out.println();
code
$ b 如果3和7应该打印:
***
****
*** **
******
*******
*******
******
** ***
****
***
现在打印出来:
*****
******
**** ***
*******
******
*****
我知道我很接近,但由于某种原因,我受到严重阻碍。
解决方案考虑到这一点:
public static void printFirstHalf(int m,int n){
if(m> n){
return;
}
//打印asterix
(int i = 1; i <= m; i ++){
System.out.print(*) ;
}
System.out.println();
//递归
printFirstHalf(m + 1,n);
}
你看到你现在用其他方法出错了吗?
如果你第一次使用递归,我明白这可能很困难,但是递归并没有魔术。逐步了解代码并理解它的功能。在这种情况下,你实际上并没有打印需要的asterix数量。坚持下去。
takes two numbers m and n on the command line and writes out a triangle pattern of asterisks
public class Triangle {
public static void main(String[] args) {
int a=0;
int b=0;
if(args.length!=0){
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
}
printFirstHalf(a,b);
printSecondHalf(a,b);
}
public static void printFirstHalf(int m, int n){
if(m==0){
return;
}
//recursive step
for(int i=m; i<=n; i++){
System.out.print("*");
}
System.out.println();
printFirstHalf(m-1,n);
}
public static void printSecondHalf(int m, int n){
if(m==0){
return;
}
printSecondHalf(m-1,n);
//recursive step
for(int i=m; i<=n; i++){
System.out.print("*");
}
System.out.println();
}
}
If 3 and 7 are sent in it should print:
***
****
*****
******
*******
*******
******
*****
****
***
Right now it prints out:
*****
******
*******
*******
******
*****
I know I am close but for some reason I am majorly stuck.
解决方案 Consider this:
public static void printFirstHalf(int m, int n){
if(m>n){
return;
}
// print asterix
for(int i=1; i<=m; i++){
System.out.print("*");
}
System.out.println();
// recurse
printFirstHalf(m+1,n);
}
Do you see where you went wrong with your other method now?
If you're working with recursion for the first time, I understand that it can be difficult but there is no 'magic' with recursion. Work through the code step-by-step and understand what it does. In this case you weren't actually printing the number of asterix needed. Keep at it.
这篇关于三角递归Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!