[英]Is there a cleaner way to write this?
我能够从赫尔辛基 MOOC 课程中找出这个项目,但我认为有一种更简洁、更易读的方式来编写它。 目标是打印出:
*****
*
***
****
**
以下是说明:“在名为“Printer”的 class 中完成方法 public static void print arrayInStars(int[] array) ,使其为数组中的每个数字打印一行星星。每行上的星星数量由数组中的相应数字定义。”
我的代码如下所示:
public static void main(String[] args) {
// You can test the method here
int[] array = {5, 1, 3, 4, 2};
printArrayInStars(array);
}
public static void printArrayInStars(int[] array) {
// Write some code in here
int i = 0;
int o = 0;
while (i < array.length) {
while (o < array[i]) {
System.out.print("*");
o++;
}
i++;
o = 0;
System.out.println("");
}
}
有没有更优雅的方式来写这个?
您的代码没有问题。 但是,由于您想要另一种方法,因此下面给出的是更紧凑的方法( 使用 for 循环):
public class Main {
public static void main(String[] args) {
int[] array = { 5, 1, 3, 4, 2 };
printArrayInStars(array);
}
public static void printArrayInStars(int[] array) {
for (int i = 0; i < array.length; i++) {
for (int o = 0; o < array[i]; o++) {
System.out.print("*");
}
System.out.println();
}
}
}
Output:
*****
*
***
****
**
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.