简体   繁体   English

java 中同时包含数字和字母的三角形

[英]triangle containing both numbers and letters in java

I want to write a Java program that prints a special triangle我想写一个打印特殊三角形的Java程序

Printing a triangle like that usually involves a loop with an index counter.打印这样的三角形通常涉及带有索引计数器的循环。

If we write down the counter value, and the ASCII code / Unicode code point for the characters, we can see a pattern we can use.如果我们记下计数器值和字符的ASCII 码/ Unicode 码点,我们可以看到可以使用的模式。

       1         0: 49
      AAA        1:    65
     33333       2: 51
    CCCCCCC      3:    67
   555555555     4: 53
  EEEEEEEEEEE    5:    69
 7777777777777   6: 55
GGGGGGGGGGGGGGG  7:    71

For even values of the index, we can print character with ASCII code i + 49 , and for odd values we print i + 64 .对于索引的偶数值,我们可以使用 ASCII 码i + 49打印字符,对于奇数值,我们可以打印i + 64

In Java 11+, it can be done as follows.在 Java 11+ 中,可以如下进行。 I'll leave it as an exercise for people to fix themselves if they need a solution for versions of Java before 11.如果人们需要针对 11 之前版本的 Java 的解决方案,我将把它作为一个练习来修复自己。

static void printTriangle(int size) {
    for (int i = 0; i < size; i++) {
        System.out.println(" ".repeat(size - i - 1) +
                           Character.toString(i + (i & 1) * 15 + 49).repeat((i << 1) + 1));
    }
}

Output when calling printTriangle(8)调用printTriangle(8)时的 Output

       1
      AAA
     33333
    CCCCCCC
   555555555
  EEEEEEEEEEE
 7777777777777
GGGGGGGGGGGGGGG

Output when calling printTriangle(10)调用printTriangle(10)时的 Output

         1
        AAA
       33333
      CCCCCCC
     555555555
    EEEEEEEEEEE
   7777777777777
  GGGGGGGGGGGGGGG
 99999999999999999
IIIIIIIIIIIIIIIIIII

Here is the correct code:这是正确的代码:

    Scanner sc = new Scanner(System.in);
    char lastChar = sc.next().charAt(0);   

    int totalLines = lastChar - 'A' + 1;

    for (int i=0; i<totalLines; i++)
    {
        for(int j=1; j<totalLines-i; j++)
            System.out.print(" ");
        
        for (int k=1; k<=2*i+1; k++)
        {
            if (i%2 == 0)
                System.out.print(i+1);
            else
                System.out.print((char)('A'+i-1));
        }
        
        System.out.println();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM