画一个直角三角形

时间:2019-06-29 00:54:30

标签: java

我是Java的新手,并且需要有关程序的一些帮助:

该程序将根据用户指定的高度triangleHeight和符号triangleChar输出直角三角形。

(1)给定程序使用*字符输出固定高度的三角形。修改给定程序以输出一个直角三角形,该直角三角形使用用户指定的triangleChar字符。 (1分)

(2)修改程序以使用嵌套循环输出高度为heightHeight的直角三角形。第一行将包含一个用户指定的字符,例如%或*。随后的每一行将有一个用户指定的附加字符,直到三角形底数达到三角形高度为止。在每个用户指定的字符之后(包括该行的最后一个用户指定的字符之后)输出一个空格。 (2分)

triangleChar =%且triangleHeight = 5的示例输出:

Enter a character:
%
Enter triangle height:
5

% 
% % 
% % % 
% % % % 
% % % % % 
import java.util.Scanner; 

public class DrawRightTriangle {
   public static void main(String[] args) {
      Scanner scnr = new Scanner(System.in);
      char triangleChar;
      int triangleHeight;

      System.out.println("Enter a character:");
      triangleChar = scnr.next().charAt(0);   

      System.out.println("Enter triangle height:");
      triangleHeight = scnr.nextInt();
      System.out.println("");

      System.out.println("*" + " ");
      System.out.println("*" + " " + "*" + " ");
      System.out.println("*" + " " + "*" + " " + "*" + " ");
   }
}

2 个答案:

答案 0 :(得分:1)

尝试一下

import java.util.Scanner; 

public class DrawRightTriangle {
   public static void main(String[] args) {
      Scanner scnr = new Scanner(System.in);
        char triangleChar;
        int triangleHeight;

        System.out.println("Enter a character:");
        triangleChar = scnr.next().charAt(0);

        System.out.println("Enter triangle height:");
        triangleHeight = scnr.nextInt();
        System.out.println("");

        for (int i = 1; i <= triangleHeight; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print(triangleChar + " ");
            }
            System.out.println();
        }
   }
}

输出:

Enter a character:
%
Enter triangle height:
5

% 
% % 
% % % 
% % % % 
% % % % % 

答案 1 :(得分:0)

这应该做您想要的:

    Scanner scnr = new Scanner(System.in);
    char triangleChar;
    int triangleHeight;

    System.out.println("Enter a character:");
    triangleChar = scnr.next().charAt(0);

    System.out.println("Enter triangle height:");
    triangleHeight = scnr.nextInt();

    int counter = 1;//Counts the number of chars for each line
    for (int i = 0; i < triangleHeight; i++) {
        String currentLine = "";
        for(int j = 0; j < counter; j++) {
            currentLine += triangleChar + " ";
        }
        System.out.println(currentLine);
        counter++;
    }