import java.util.Scanner;
public class diamond {
public static void main (String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("Please enter an integer");
int lines = scan.nextInt();
for(int counter = 1; counter <= lines; counter++)
{
if (counter%2 != 0)
{
for(int count2 = 1; count2 <= counter; count2++){
System.out.print("*");
}
System.out.println();
}
}
}
}
我应该向用户询问一些行并输出一个由星号组成的钻石。我需要一些帮助来弄清楚如何使星号居中。我知道对于字符串有一些String.utils方法或其他东西,但输出是基于for循环的碎片,所以我不认为这真的有效。如果确实如此,请务必告诉我。
答案 0 :(得分:1)
您需要在每行之前打印一定量的空格。然后,你需要另一个for循环反之。 试试这段代码:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter an integer ");
int lines = scan.nextInt();
for (int counter = 1; counter <= lines; counter++) {
if (counter % 2 != 0) {
for (int i = 0; i < lines - (counter / 2) - 3; i++) {
System.out.print(" ");
}
for (int count2 = 1; count2 <= counter; count2++) {
System.out.print("*");
}
System.out.println();
}
}
for (int counter = lines - 1; counter >= 1; counter--) {
if (counter % 2 != 0) {
for (int i = 0; i < lines - (counter / 2) - 3; i++) {
System.out.print(" ");
}
for (int count2 = 1; count2 <= counter; count2++) {
System.out.print("*");
}
System.out.println();
}
}
}
答案 1 :(得分:1)
我认为你应该准备一个字符串在每一行打印出来,然后你会知道它有多少个字符,当行增加时,删除字符串中心的两个'*'并添加一个“”在它前面,然后再打印出来。