[英]Is there a cleaner way to write this?
I was able to figure out this project from the Helsinki MOOC course, but I think there is a cleaner and easier to read way to write it.我能够从赫尔辛基 MOOC 课程中找出这个项目,但我认为有一种更简洁、更易读的方式来编写它。 The goal was to print out:
目标是打印出:
*****
*
***
****
**
And here are the directions: "Complete the method public static void print arrayInStars(int[] array) in the class named 'Printer' to make it print a row of stars for each number in the array. The amount of stars on each row is defined by the corresponding number in the array."以下是说明:“在名为“Printer”的 class 中完成方法 public static void print arrayInStars(int[] array) ,使其为数组中的每个数字打印一行星星。每行上的星星数量由数组中的相应数字定义。”
My code looks like this:我的代码如下所示:
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("");
}
}
Is there a more elegant way to write this?有没有更优雅的方式来写这个?
There is no problem with your code.您的代码没有问题。 However, since you want another way of doing it, given below is a more compact one ( using for loop ):
但是,由于您想要另一种方法,因此下面给出的是更紧凑的方法( 使用 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: Output:
*****
*
***
****
**
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.