gpt4 book ai didi

java - Java中在一行中间打印一个单词

转载 作者:太空宇宙 更新时间:2023-11-04 13:51:59 24 4
gpt4 key购买 nike

我打印了一个等边三角形,并在某一行的中间我想打印一个单词(作为输入)。我的代码如下:

for (int rows=1; rows <= getHeight(); rows++)
{
char charToPrint = '*';
if(rows == getRowNum()){
for(int i=0;i<getTextLabel().length();i++){
charToPrint = getTextLabel().charAt(i);
}
}
for (int spaces=1; spaces <= number_of_stars; spaces++)
{
System.out.print(" ");
}
for (int star=1; star <= rows; star++)
{
System.out.print(charToPrint);
System.out.print(" ");
}
System.out.println("");
number_of_stars = number_of_stars - 1;
}

输出:

          * 
* *
* * *
* * * *
* * * * *
* * * * * *
A A A A A A A
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *

但我希望输出是这样的:

          * 
* *
* * *
* * * *
* * * * *
* * * * * *
* L R E Z A *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *

最佳答案

您可以尝试以下代码,因为它似乎适用于输入LREZA:

 public static void main(String[] args) {
int userRowNumber = 15;
int height = 20;
int number_of_stars = height;
String charToPrint;
String inputWord = "LREZA";
int inputSize = inputWord.length();
if(userRowNumber < (inputSize*2) ) {
System.out.println("Not enough space in row to display input text");
return;
}
for (int rows=1; rows <= height; rows++)
{
charToPrint = "*";
if(rows == userRowNumber)
{
int startWordFrom = (userRowNumber - inputWord.length())/2;
printSpace(number_of_stars);
for (int spaces=0; spaces <rows; spaces++)
{
if(spaces >= startWordFrom && spaces <(inputSize*2) ) {
System.out.print(inputWord.charAt(spaces-startWordFrom));
System.out.print(" ");

} else {
System.out.print("*");
System.out.print(" ");
}
}
System.out.println("");
number_of_stars--;
rows++;
}
printSpace(number_of_stars);
printCharacter(charToPrint,rows);
System.out.println("");
number_of_stars = number_of_stars - 1;
}
}
public static void printSpace(int number_of_stars) {
for (int spaces=1; spaces <= number_of_stars; spaces++)
{
System.out.print(" ");
}
}
public static void printCharacter(String charToPrint, int numberOfTimes) {
for (int star=1; star <= numberOfTimes; star++)
{
System.out.print(charToPrint);
System.out.print(" ");
}
}

处理输入字符串时需要注意一些要点。我们需要尝试集中输入,并且还需要在每个输入字母后面放置一个空格。我从这个程序中得到的输出是:

                    * 
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * * * * *
* * * * * * * * * * * * * *
* * * * * L R E Z A * * * * *
* * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * *

这是我所期望的。

关于java - Java中在一行中间打印一个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30204915/

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