嵌套循环模式java

时间:2015-06-06 10:09:32

标签: java nested-loops bluej

我一直在努力使用这种模式,试图只使用嵌套FOR循环所需的代码。我不需要使用模式,只需要嵌套 for 循环:

123454321
1234 4321
123   321
12     21
1       1

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

2 个答案:

答案 0 :(得分:4)

你走了。一个嵌套的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);

答案 1 :(得分:0)

您应该认真考虑修改您的问题并更具体。此外,你真的不需要嵌套循环,这种方式似乎效率低下。但是,既然你需要,这是一个天真的解决方案:

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);
}