更改与Java中的嵌套循环相关的输出

时间:2015-11-06 03:36:31

标签: java nested-loops

import static java.lang.System.*; 
import java.util.Scanner;

public class TriangleFour{

 public static void createTriangle(int size, String let){
  String output = "";
  String x = let;
  int y = size;

  for (int z = size; z > 0; z--){
     int p = z;
     output += "\n";

     while (p > 0){
      output = output + " ";
      p--;
     }

     for (int d = size; d >= y; d--){
      output = output + x;
     }

     y--;
  }//End of for loop

  out.println(output);
 }
}

在我的程序中执行此语句TriangleFour.createTriangle(3, "R");时,此代码会产生以下输出:

  R
 RR
RRR

我想修改我的代码,基本上像这样翻转输出:

RRR
 RR
  R

任何帮助都将不胜感激。

4 个答案:

答案 0 :(得分:1)

这是我的尝试。我稍微减少了你的代码,并重命名了一些变量以使其更清晰。

public static void createTriangle(int size, String let){
        for(int i=size;i>0;i--){
            int fill = i;
            int space = size-i;
            while(space>0){
                System.out.print(" ");
                space--;
            }
            while(fill>0){
                System.out.print(let);
                fill--;
            }
            System.out.println();   
        }
    }

几乎第一个for循环决定了会有多少行。如果size为3,则会有3行。第一个while循环控制每行的空白量。 space是要打印的空格数,fill是要打印的字母数。每次循环运行时,您都希望space + fill = size

因此,在第一个循环中,space为0.您不打印任何空格。 fill为3,因此您打印3个字母,0 + 3 = 3。

RRR

第二个循环,space为1,打印1个空格。 fill为2,打印2个字母,1 + 2 = 3。

RRR
 RR

第3次循环,space为2,打印2个空格。 fill为1,打印1个字母。 2 + 1 = 3

RRR
 RR
  R

希望这是有道理的。

答案 1 :(得分:1)

我希望你只是想打印它。在编码之前先尝试调试或先编写算法

public static void createTriangle(int size, String let) {
        StringBuilder sb= new StringBuilder();
        for(int i=0;i<3;i++){
            sb.append(let);
            System.out.println(sb.toString());
        }

    }

答案 2 :(得分:0)

你只需修改打印空间的条件[&#34; &#34;]和角色 如下所示

   student_ID=c(rep("1001",8),rep("1002",3),rep("1005",11))
   Year=c(rep(2011,4),rep(2012,4),2011,2012,2013,rep(2011,4),rep(2012,3),rep(2013,4))
   Grade=c(rep("Fail",2),rep("Pass",3),rep("Fail",3),rep("Pass",7),rep("Fail",2),rep("Pass",5))
   Unitcode<-c(1201:1222)
   record<-data.table(student_ID, Year, Grade, Unitcode)

答案 3 :(得分:0)

请尝试以下代码(我已经测试过):

public class TriangleFour {
    public static void main(String[] args) {
        createTriangle(3, "R");
    }

    public static void createTriangle(int size, String let) {
        String output = "";
        String x = let;
        int y = size;
        for (int z = 0; z < size; z++) {
            int p = z;
            output = output + "\n";
            while (p > 0) {
                output = output + " ";
                p--;
            }
            for (int d = 0; d < y; d++) {
                output = output + x;
            }
            y--;
        }
        System.out.println(output);
    }
}

输出:

RRR
 RR
  R