简体   繁体   English

如何使方法根据传入的参数在一定时间内执行某些操作?

[英]How can I make a method do something a certain amount of times based on a parameter that is passed in?

public void printStars(int level) {

    for (int one = level; one >= 1; one--) {

        for (int two = one; two <= level; two++) {


            System.out.print("*");

        }
        System.out.println();


    }
}

I am trying to make something that looks like this: 我正在尝试制作如下所示的内容:

    *
   ***
  *****
 *******
*********

Currently I am getting about half of the correct diagram all left aligned. 目前,我得到了大约一半的正确图表。

I tried to incorporate printf, but I realized that it wouldn't work because the value of level cannot be transferred to the printf method. 我尝试合并printf,但是我意识到这是行不通的,因为level的值无法转移到printf方法中。 I was also wondering if there was a way to set the longest segment (the bottom) equal to (2 * level) - 1 stars long and apply some sort of formatting on that to get the answer? 我还想知道是否有办法将最长的段(底部)设置为等于(2 *级)-1星长,并对其应用某种格式以获得答案?

Print appropriate number of spaces ahead 在前面打印适当数量的空格

public void printStars(int level) {

    for (int one = level; one >= 1; one--) {
        for(int k=1, k<one;k++){  // print appropriate number of spaces before
            System.out.print(" "); 
        }    
        for (int two = 1; two <=2*(level-one)+1; two++) {
            System.out.print("*");
        }
        System.out.println();
    }
}

Explanation: 说明:

  1. if there are N levels in total, and last line doens't have any space. 如果总共有N个级别,并且最后一行没有任何空格。 => N-1 levels will have spaces with N-1 in first line, N-2 in 2nd line, so on.. 1 in (N-1)th line. => N-1级别的空格将在第一行中包含N-1,在第二行中包含N-2,依此类推...在第(N-1)行中包含1。

  2. Number of stars: (level-one) gives the line you are printing minus 1, because, initially when one = level (one-level = 0), its 1st line, next its (level-one) = 1, because one is decreased. 星数:(一级)给您打印的行减1,因为最初当一个=一级(一级= 0)时,它是第一行,下一行(一级)= 1,因为一个是降低。 & in each line you have to print, 2*X +1 *'s, &在每行中必须打印2 * X +1 *,

Try below: 请尝试以下方法:

public static void printStars(int level) {
    for (int one = 0; one < level; one++) {
      for(int space = 1; space < (level-one); space++){ //<- print leading space
       System.out.print(" ");
      }

      //<- print stars in odd numbers e.g. 1,3,5,7
      for (int two = 0; two < 2*one+1; two++) { 
       System.out.print("*");
      }
      System.out.println();
   }
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM