嵌套循环模式 java

nested loops pattern java

我一直在为这个模式苦苦挣扎,试图只使用嵌套 FOR 循环所需的代码。我被要求不要使用模式,只是一个嵌套的 for 循环:

123454321
1234 4321
123   321
12     21
1       1

所需的代码是 Java,我正在使用 BlueJ 编译器。

给你。嵌套的 for 循环,可提供所需的输出。

String s[] = new String[]{"123454321","1234 4321","123   321","12     21","1       1"};
for(int i=0; i<=0;i++)// for the nested loop
  for(String x:s)
    System.out.println(x);

您应该认真考虑修改您的问题并更具体一些。另外,你真的不需要嵌套循环,这样看起来效率很低。但是,由于您需要这样做,这里有一个天真的解决方案:

final int LIMIT = 5; //LIMIT has to be <10

//first construct a char array whose maximum number is LIMIT
char[] input = new char[2*LIMIT-1];     
//if you use Arrays.fill(input, ' '); here, and a print in the first loop, you get the reverse answer (try it)           
for (int i = 0; i<LIMIT; ++i) {
    input[i] = Character.forDigit(i+1, 10); //converts int to char (in decimal)
    input[(2*LIMIT)-i-2] = input[i];        
}


//next print the array, each time removing the chars that are within an increasing range from the middle element of the array    
for (int i = LIMIT; i > 0; --i) {            
    for (int j = 0; j < LIMIT-i; ++j) { //you don't really need a nested loop here
        input[LIMIT-1+j] = ' '; //replace the j chars following the middle with whitespace
        input[LIMIT-1-j] = ' '; ////replace the j chars before the middle with whitespace
    }
    System.out.println(input);
}

没有嵌套循环的替代方案是:

//after the first loop
String line = input.toString();

System.out.println(line);
for (int i = LIMIT; i>0; --i) {
    line = line.replace(Character.forDigit(i, 10), ' ');
    System.out.println(line);
}