以错误顺序打印三角形字符以及不需要的字符
问题描述:
该程序的目的是让用户决定三角形的长度(行),并决定它应该朝上还是朝下。和三角形是由字母,所以它应该是这个样子:以错误顺序打印三角形字符以及不需要的字符
How many rows would you like? (finish with -1): 4
Do you want the triangle to face up (1) or down (2)? 1
A
A B
A B C
A B C D
How many rows would you like? (finish with -1): 6
Do you want the triangle to face up (1) or down (2)? 2
A B C D E F
A B C D E
A B C D
A B C
A B
A
我有两个问题,当我试图让三角打印面朝下,第一个字母是这样的(它应该开始与一个)
F E D C B A
F E D C B
F E D C
F E D
F E
F
而字母后面加载我不想要的不同字符的负载。我尝试了很多东西,似乎没有任何工作。我真的可以使用一些建议。
这是我到目前为止的代码:
import java.util.Scanner;
public class Triangle {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
int a = 0;
int b = 0;
while (a != -1) {
System.out.println("How many rows would you like? (finish with -1):");
a = scan.nextInt();
if (a != -1) {
b = a - 1;
int j = 'A';
char alphabet = (char) (j + 'A');
System.out.println("Do you want the triangle to face up (1) or down (2)?");
int c = scan.nextInt();
if (c == 1) {
for (int i = 1; i <= b + 'A'; i++) {
for (j = 'A'; j <= i; j++)
System.out.print((char) j + " ");
System.out.println(alphabet);
}
} else {
for (int i = 1; i <= b + 'A'; i++) {
for (j = b + 'A'; j >= i; j--)
System.out.print((char) j + " ");
System.out.println(alphabet);
}
}
}
}
}
}
答
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int a = 0;
int b = 0;
while (a != -1) {
System.out.println("How many rows would you like? (finish with -1):");
a = scan.nextInt();
if (a != -1) {
System.out.println("Do you want the triangle to face up (1) or down (2)?");
int c = scan.nextInt();
if (c == 1) {
for (int i = 0; i < a; i++) {
for (int j = 0; j <= i; j++) {
System.out.print((char) (j + 'A'));
}
System.out.println();
}
} else {
for (int i = 0; i < a; i++) {
for (int j = a; j > i; j--) {
System.out.print((char) (a - j + 'A'));
}
System.out.println();
}
}
}
}
}
答
采用下面给出一个更加模块化的解决方案。 它打印由四行组成的三角形,一个朝上,另一个朝下。
public static void main(String args[]) {
int a = 4; // # of rows
// Triangle facing up
for (int i = 1; i <= a; i++) // i - How many letters in this row (also row No)
printRow(i);
System.out.println("--------"); // Separator
// Triangle facing down - Start from the longest row, then decrease its length
for (int i = a; i > 0; i--)
printRow(i);
}
static void printRow(int length) {
for (int j = 0; j < length; j++) // j - char code shift
System.out.printf("%c ", j + 'A');
System.out.println();
}
该解决方案更优雅,因为打印行的代码不会重复。
还要注意一种更自然的方式来表示连续行的长度:对于朝下的三角形减少了行长度。