打印星号根据数组中的整数 – Java

huangapple go评论77阅读模式
英文:

Print stars according to the integers in an Array - Java

问题

在这个练习中,我必须编写一个方法,根据整数数组的值打印星号。最终我成功让我的代码通过了,但我并没有完全明白为什么要将整数star的初始值设为1,而不是0。为什么是1而不是0?有人能给我解释一下吗?
非常感谢!

public class Printer {

    public static void main(String[] args) {
        // You can test the method here
        int[] array = {1,2,5,10};
        printArrayInStars(array);
    }

    public static void printArrayInStars(int[] array) {
        // Write some code in here
        for (int index = 0; index < array.length; index++) {
            int number = array[index];

            for (int star = 1; star <= number; star++) {
                System.out.print("*");

            }
            System.out.println("");
        }
    }
}
英文:

In this exercise I had to write a method to print stars according to the integers of an array. I have finally got my code to pass, but I did not understand exactly why. The initial value of the integer star is 1, as 0 would not work properly. Why 1 and not 0? Can any of you give me the explanation?
Thank u loads!

public class Printer {

    public static void main(String[] args) {
        // You can test the method here
        int[] array = {1,2,5,10};
        printArrayInStars(array);
    }

    public static void printArrayInStars(int[] array) {
        // Write some code in here
        for (int index = 0; index &lt; array.length; index++) {
            int number = array[index];

            for (int star = 1; star &lt;= number; star++) {
                System.out.print(&quot;*&quot;);

            }
            System.out.println(&quot;&quot;);
        }
    }
}

答案1

得分: 0

这是正常的。你的循环应该是这样的:

for (int star = 0; star < number; star++)

或者

for (int star = 1; star <= number; star++)
英文:

it's normal. your loop should be something like :

for (int star = 0; star &lt; number; star++)

or

for (int star = 1; star &lt;= number; star++)

huangapple
  • 本文由 发表于 2020年8月13日 01:57:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/63382243.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定