[英]Number pyramind, with recursive method. Java Beginner
I am a new member here, and I am also a beginner in JAVA. 我是这里的新成员,也是JAVA的初学者。 The thing that seems the most abstract to me is recursion, and so I have some difficulties finishing a program that should have this output if we write 3 for example:
对我来说,最抽象的东西是递归,因此,例如编写3时,我很难完成一个应该具有此输出的程序:
1 1个
12 12
123 123
12 12
1 1个
Or if we write 5 for example it should print out this: 或者,例如,如果我们写5,它应该打印出来:
1 1个
12 12
123 123
1234 1234
12345 12345
1234 1234
123 123
12 12
1 1个
And I can do this program with for loop, but I have to use recursion, and here is what I have done so far: 我可以使用for循环来执行此程序,但是我必须使用递归,这是我到目前为止所做的:
public class Aufgabe3 {
private static void printSequenz(int n) {
if(n<1){
return;
}
printMany(n);
printSequenz(n-1);
}
private static void printMany(int n){
for(int i=1;i<=n;i++){
System.out.print(i);
}
System.out.println();
}
public static void main(String[] args) {
printSequenz(5);
}
}
I would be really happy if someone would help me :). 如果有人能帮助我,我将非常高兴:)。
You need to implement two recursive functions: 您需要实现两个递归函数:
void printLoToHi(int n)
{
if (n < 1)
return;
printLoToHi(n-1);
printMany(n);
}
void printHiToLo(int n)
{
if (n < 1)
return;
printMany(n);
printHiToLo(n-1);
}
Then, you need to call them sequentially: 然后,您需要依次调用它们:
printSequenz(int n)
{
printLoToHi(n);
printHiToLo(n-1); // -1 in order to avoid printing the highest twice
}
Or in a more "symmetrical manner": 或更“对称”地:
printSequenz(int n)
{
printLoToHi(n-1); // print lowest to second highest
printMany(n); // print the highest
printHiToLo(n-1); // print second highest to lowest
}
You could do it like this: 您可以这样做:
private static void printSequenz(int n) {
printSequenz(1,n, true);
}
private static void printSequenz(int current, int total, boolean goingUp) {
if(!goingUp && current<1){
return;
}
printMany(current);
if(current+1>total){
goingUp=false;
}
if(goingUp){
printSequenz(current+1,total,goingUp);
} else {
printSequenz(current-1,total,goingUp);
}
}
private static void printMany(int n) {
for (int i = 1; i <= n; i++) {
System.out.print(i);
}
System.out.println();
}
public static void main(String[] args) {
printSequenz(5);
}
public class Test {
public static void main(String args[]) {
int seq = 6;
for(int i=1; i<=seq; i++) {
System.out.println("");
int low =seq-(seq-i);
printIncreasing(i,low);
}
for(int i=seq-1; i>=1; i--) {
System.out.println("");
int low = seq-i;
printDecreasing(i,low);
}
}
public static void printIncreasing(int high, int low) {
for(int i = 1; i<=high;i++ ) {
System.out.print(i);
}
}
public static void printDecreasing(int high, int low) {
for(int i = 1; i<=high;i++ ) {
System.out.print(i);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.