所以基本上我的程序会在用户输入一个模数 8 等于 0 的数字时打印这种类型的三角形。所以一个较大的三角形是由一个底数为 4 的较小三角形组成的。这就是我输入数字时三角形的样子16:
* * * * * * * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * *
* * * *
* * * * * * * * * * * *
* * * * * * * * *
* * * * * *
* * *
* * * * * * * *
* * * * * *
* * * *
* *
* * * *
* * *
* *
*
但我的结果是这样的:
* * * * * * * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * *
* * * *
* * * * * * * * * * * *
* * * * * * * * *
* * * * * *
* * *
* * * * * * * *
* * * * * *
* * * *
* *
* * * *
* * *
* *
*
我不太确定如何添加空格。有人可以帮我吗?这是我的代码:
...
System.out.println("Please enter the length:");
int length = scan.nextInt();;
//length must be longer than 2
if (length <= 1){
System.out.println("Sorry :(! Length must be 2 or higher");
}
//if user enter a number that can divide by 8 and has no remainder, then
//loop to print out a beautiful triangle
else if(length%8==0) {
int numOfTriangle = length/4;
System.out.println("Here is your beautiful triangle :D \n");
for (int rowOfTri = numOfTriangle; rowOfTri > 0; rowOfTri--){
for(int i = 0; i < rowOfTri; i++){
printBase();
}
System.out.println();
for(int i = 0; i < rowOfTri; i++){
printThree();
}
System.out.println();
for(int i = 0; i < rowOfTri; i++){
printTwo();
}
System.out.println();
for(int i = 0; i < rowOfTri; i++){
printOne();
}
System.out.println();
}
System.out.println();
}
//any other number will print a normal triangle
else{
System.out.println("Here is your beautiful triangle :D \n");
for (int i = 1; i <= length; i++){
for (int j = 1; j <= length; j++){
if (j < i){
System.out.print(" ");
} else {
System.out.print("*");
System.out.print(" ");
}
}
System.out.println();
}
}
//asking users if they want to print again
System.out.println("\nDo you want to print another triangle? Type Yes or No.");
//scan for string answer
String againChoice = scan.next();
//if answer start with Y or y then answer is Yes.
if(againChoice.startsWith("Y") || againChoice.startsWith("y")){
printAgain = true;
}
//if answer start with N or n then answer is No.
else if(againChoice.startsWith("N") || againChoice.startsWith("n")){
printAgain = false;
System.out.println("Bye!");
}
// set input to none again
} while (printAgain == true);
}
//methods to print a triangle
public static void printBase(){
System.out.print("* * * * ");
}
public static void printThree(){
System.out.print(" * * * ");
}
public static void printTwo(){
System.out.print(" * * ");
}
public static void printOne(){
System.out.print(" * ");
}
public static void printSpace(){
System.out.print(" ");
}
}