如何用高度Java三角形图案打印

时间:2017-01-24 12:57:19

标签: java

嗨,我想尝试这样做,如果身高是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

4 个答案:

答案 0 :(得分:0)

您的代码只打印&#39; A&#39;就像您编码的那样,您想要打印双AA,即&#39; AA&#39;。

在每一次奇数迭代之后,即1,3,5,7 ......,你想打印BB&#39;太。然后,这将在你的第二个循环中,即使&#39;。

for i < height
  if i % 2 is 0
    print 'BB'
  else
    print 'AA'
  print newline
像这样。

答案 1 :(得分:0)

您也可以删除内部循环

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);
}
}

它将打印您想要的内容,在每次迭代中,您在res中添加AA或BB

答案 2 :(得分:0)

使用此代码示例

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();
        }

    }
}

答案 3 :(得分:-1)

另一种解决方案......

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;
}