英文:
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 < array.length; index++) {
int number = array[index];
for (int star = 1; star <= number; star++) {
System.out.print("*");
}
System.out.println("");
}
}
}
答案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 < number; star++)
or
for (int star = 1; star <= number; star++)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论