gpt4 book ai didi

java - 需要帮助将文本输出居中

转载 作者:行者123 更新时间:2023-11-30 04:13:19 26 4
gpt4 key购买 nike

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 循环的,所以我认为这在这里不起作用。如果确实如此,请务必让我知道。

最佳答案

您需要在每行之前打印一定数量的空格。然后,您将需要另一个 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();
}
}
}

关于java - 需要帮助将文本输出居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19073603/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com