[英]How to Java Triangle pattern printing with height
嗨,如果高度为 3,我正在尝试执行此操作
AA
BBAA
AABBAA
如果高度为7,则打印以下图案
AA
BBAA
AABBAA
BBAABBAA
AABBAABBAA
BBAABBAABBAA
AABBAABBAABBAA
到目前为止,我做了这个
import java.util.Scanner;
public class P4 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int height;
String A = "AA";
String B = "BB";
Scanner sc = new Scanner(System.in);
System.out.println("Enter your height: ");
height = sc.nextInt();
for(int i = 0; i < height+1; i++) {
for(int j = 0; j < i; j++) {
System.out.print("A");
}
System.out.println();
}
}
}
我的输出是
Enter your height:
3
A
AA
AAA
你的代码只打印'A',就像你编码一样,你想打印双AA,即'AA'。
在每次奇数迭代后,即 1,3,5,7...,您也想打印 'BB'。 这将在您的第二个循环中,“如果甚至”。
for i < height
if i % 2 is 0
print 'BB'
else
print 'AA'
print newline
像这样。
您也可以删除内部循环
public static void main(String[] args) {
int height;
String A = "AA";
String B = "BB";
String res="";
Scanner sc = new Scanner(System.in);
System.out.println("Enter your height: ");
height = sc.nextInt();
for(int i = 1; i <= height; i++) {
if(i%2==0){
res=B+res;
}else{
res=A+res;
}
System.out.println(res);
}
}
它将打印您想要的内容,在每次迭代时,您都会在资源中添加 AA 或 BB
使用此代码示例
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("Hello World!");
int height;
String A = "AA";
String B = "BB";
Scanner sc = new Scanner(System.in);
System.out.println("Enter your height: ");
height = sc.nextInt();
for (int i=1; i<=height; i++){
for (int j=1; j<=i; j++) {
if ((j%2) == 1) {
System.out.print((i%2 == 1) ? A: B);
} else {
System.out.print((i%2 == 1) ? B :A);
}
}
System.out.println();
}
}
}
另一种解决方案...
public static final String A = "AA";
public static final String B = "BB";
public static void main(String[] args) {
System.out.println("Input your height");
final Scanner inputScanner = new Scanner(System.in);
int height = inputScanner.nextInt();
String currentToken;
for(int i = 0; i < height; i++){
currentToken = i%2==1?B:A;
for(int j = i; j >= 0; j--){
System.out.print(currentToken);
currentToken = changeToken(currentToken);
}
System.out.print("\n");
}
}
private static String changeToken(String currentToken){
return currentToken.equals(A)?B:A;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.