编写一个程序,要求用户输入一个整数(n)并打印n行输出

时间:2016-10-30 21:21:34

标签: java loops

编写一个程序,要求用户输入一个整数(n)并打印n行输出,第一行有n个字符,第二行有n-1个字符,......,最后一行有1个字符。每行必须以字符“A”开头。第一行的字符数为n,字符为

A b C d E f G h I j K l M n O p Q r S t U v W x Y z 

这是我的代码:

System.out.println("How many rows for Pattern 2?: ");
        int p2 = input.nextInt();
        String s = input.nextLine();

        char ch;
        int i1 , j1;
        for(i1 = p2; i1 >= 1; i1--){
            ch = 'A';
            for(j1 = 1; j1 <= i1; j1++){
                System.out.print(" " + ch++);

            }

当我尝试运行程序时

我收到了这个字符串:

How many rows for Pattern 2?: 
16
 A B C D E F G H I J K L M N O P
 A B C D E F G H I J K L M N O
 A B C D E F G H I J K L M N
 A B C D E F G H I J K L M
 A B C D E F G H I J K L
 A B C D E F G H I J K
 A B C D E F G H I J
 A B C D E F G H I
 A B C D E F G H
 A B C D E F G
 A B C D E F
 A B C D E
 A B C D
 A B C
 A B
 A

如何获得这样的输出:

How many rows for Pattern 2?: 7

    A b C d E f G
    A b C d E f
    A b C d E
    A b C d
    A b C
    A b
    A 

3 个答案:

答案 0 :(得分:0)

如果j1可被2整除,请将j1中的字符作为'a' + j1 - 1获取。 如果j1不能被2整除,则将j1中的字符作为'A' + j1 - 1获取。 (请注意不同的基础:'a''A'。)

您可以通过更改内部循环的内容来实现它:

for (j1 = 1; j1 <= i1; j1++) {
    if (j1 % 2 == 0) {
        ch = (char)('a' + j1 - 1);
    } else {
        ch = (char)('A' + j1 - 1);
    }
    System.out.print(" " + ch);
}
System.out.println();

答案 1 :(得分:0)

import java.util.Scanner;


public class MyPattern {


@SuppressWarnings("resource")

    public static void main(String[] args) {

    //Store the letters you desire in an array of strings
    String[] letters = {"A", "b", "C", "d", "E", "f", "G", "h", "I", "j" , "K" ,"l","M", "n", "O", "p", "Q" , "r", "S", "t", "U", "v" ,"W" ,"x" ,"Y" ,"z"}; 

    //create a Scanner object to take input from user
    Scanner scan = new Scanner(System.in);
    System.out.print("How many rows for Pattern 2?: ");
    int rows = scan.nextInt();

    if(rows > 26 || rows < 1) throw new IllegalArgumentException("Wrong input");  //as u know, number of alphabetics is 26

    //nested for-loop to print the required output
      for(int i = 0; i < rows; i++) {
          for(int j = 0; j < rows - i; j++) {
              System.out.print(letters[j] + " ");
          }

          System.out.println();
      }

         scan.close();
   }


}

这绝对可以有效而干净地解决您的问题。

答案 2 :(得分:-1)

您只需在打印前调用Character.toLowerCase(char)方法。用以下内容替换您的打印行:

System.out.print(" " + (j1 % 2 = 0 ? Character.toLowerCase(ch++) : ch++));