[英]Need help centering text output
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();
}
}
}
}
I am supposed to ask the user for a number of lines and output a diamond made of asterisks that number of lines tall. 我应该问用户输入多少行,并输出由行数高的星号制成的钻石。 I need some help figuring out how to center the asterisks. 我需要一些帮助来弄清楚如何使星号居中。 I know for strings there is some String.utils method or something, but the output comes in pieces based on a for loop, so I don't think that really works here. 我知道对于字符串来说,有一些String.utils方法之类的东西,但是输出是基于for循环的,因此我认为这在这里并不起作用。 If it does, by all means let me know though. 如果可以,请一定让我知道。
You need to print a certain amount of spaces before each line. 您需要在每行之前打印一定数量的空格。 Then, you would need another for loop for the opposite. 然后,您将需要另一个for循环来执行相反的操作。 Try this code: 试试这个代码:
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();
}
}
}
我认为您应该准备一个字符串以在每行上打印出来,然后您将确切知道它有多少个字符,当行增加时,请删除字符串中心的两个“ *”并在其前面添加一个“” ,然后再次打印出来。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.