我打印了一个等边三角形,在某一行的中间我想打印一个单词(作为输入)。我的代码如下:
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 *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *
答案 0 :(得分:0)
您可以尝试以下代码,因为它似乎适用于输入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 * * * * *
* * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * *
我认为这是预期的。