在Java中将*打印为三角形?

时间:2012-12-26 23:31:48

标签: java loops

我在Java课程中的任务是制作3个三角形。一个左对齐,一个右对齐,一个居中。我必须为什么类型的三角形创建一个菜单,然后输入需要多少行。三角形必须看起来像这样

*
**
***
****


   *
  **
 ***
****


  *
 ***
*****

到目前为止,我能够做左对齐的三角形,但我似乎无法得到另外两个。我试过谷歌搜索但没有出现。有人可以帮忙吗?到目前为止,我有这个。

import java.util.*;
public class Prog673A
{
    public static void leftTriangle()
    {
        Scanner input = new Scanner (System.in);
        System.out.print("How many rows: ");
        int rows = input.nextInt();
        for (int x = 1; x <= rows; x++)
        {
            for (int i = 1; i <= x; i++)
            {
                System.out.print("*");
            }
            System.out.println("");
        }
    }
    public static void rightTriangle()
    {
        Scanner input = new Scanner (System.in);
        System.out.print("How many rows: ");
        int rows = input.nextInt();
        for (int x = 1; x <= rows; x++)
        {
            for (int i = 1; i >= x; i--)
            {
                System.out.print(" ");
            }
            System.out.println("*");
        }
    }
    public static void centerTriangle()
    {

    }
    public static void main (String args [])
    {
        Scanner input = new Scanner (System.in);
        System.out.println("Types of Triangles");
        System.out.println("\t1. Left");
        System.out.println("\t2. Right");
        System.out.println("\t3. Center");
        System.out.print("Enter a number: ");
        int menu = input.nextInt();
        if (menu == 1)
            leftTriangle();
        if (menu == 2)
            rightTriangle();
        if (menu == 3)
            centerTriangle();
    }
}

示例输出:

Types of Triangles
1.  Left
2.  Right
3.  Center
Enter a number (1-3):  3
How many rows?: 6

     *
    ***
   *****
  *******
 *********
***********

21 个答案:

答案 0 :(得分:15)

提示:对于每一行,您需要首先打印一些空格,然后打印一些星星。 每行的空格数应减少一个,而星数应增加。

对于居中的输出,每行增加 2 的星数。

答案 1 :(得分:6)

Ilmari Karonen有很好的建议,我只想稍微概括一下。一般来说,在你问“我怎么能让电脑做这个?”之前问“怎么这样做?”

所以,如果有人给你一个空Word文档并要求你创建三角形,你会怎么做呢?无论您想出什么解决方案,通常都不难将其转换为Java(或任何其他编程语言)。它可能不是最好的解决方案,但(希望!)它可以工作,它可能会为您提供更好的解决方案。

所以,例如,也许你会说你输入基数,然后上一行,然后键入下一个最高行等。这表明你可以在Java中做同样的事情 - 创建一个列表字符串,从顶部到顶部,然后反转它们。这可能表明你可以按相反的顺序创建它们,然后不必反转它们。然后 可能会建议您不再需要该列表,因为您只需要以相同的顺序创建和打印它们 - 此时您基本上就已经提出了Ilmari卡罗宁的建议。

或许,也许你想出了另一种做法 - 也许你会更直接地想出Ilmari Karonen的想法。无论如何,它应该可以帮助您解决这个问题以及许多其他问题。

答案 2 :(得分:2)

左三角形 -   *   **

from above pattern we come to know that-
1)we need to print pattern containing n rows (for above pattern n is 4).
2)each  row contains star and no of stars i each row is incremented by 1.
So for Left alinged triangle we need to use 2 for loop.
1st "for loop" for printing n row.
2nd  "for loop for printing stars in each rows. 


 Code for  Left alinged triangle-

 public static void leftTriangle()
{
       /// here  no of rows is 4
 for (int a=1;a<=4;a++)// for loop for row
 {   
 for (int b=1;b<=a;b++)for loop for column
 {
 System.out.print("*");
 }

System.out.println();}
}

右三角形 -    *
  **

from above pattern we come to know that-
1)we need to print pattern containing n rows (for above pattern n is 4).
 2)In each  row we need to print spaces followed by a star & no of spaces            in each row is decremented by 1.
 So for Right alinged triangle we need to use 3 for loop.
 1st "for loop" for printing n row.
 2nd  "for loop for printing spaces.
 3rd "for loop" for printing stars.

Code for Right alinged triangle -

public void rightTriangle()
{
    // here 1st print space and then print star
  for (int a=1;a<=4;a++)// for loop for row
 { 
 for (int c =3;c>=a;c--)// for loop fr space
 {  
 System.out.print(" ");
 }
 for (int d=1;d<=a;d++)// for loop for column
 { 
 System.out.print("*");   
 }
 System.out.println(); 
 }
 }

中心三角 -    *
  * *

从上面的模式我们开始知道 -    1)我们需要打印包含n行的图案(对于上面的图案n是4)。    2)在每行中我们需要打印空格,然后是星号和星号。再一个空间。开始时每行中的空格NO减1。    所以对于右三角形,我们需要使用3 for循环。    用于打印n行的第一个“for循环”。    第二个“用于打印空间的循环。    印刷明星的第3个“for loop”。

中心三角代码 -

public  void centerTriangle()
{   
for (int a=1;a<=4;a++)// for lop for row
{   
for (int c =4;c>=a;c--)// for loop for space
{  
System.out.print(" ");
}
for (int b=1;b<=a;b++)// for loop for column
{
System.out.print("*"+" ");
}
System.out.println();}
}

打印所有3种图案的代码 -     公共阶层空间4     {     public static void leftTriangle()     {            ///这里没有行是4      for(int a = 1; a&lt; = 4; a ++)// for for循环      {
     for(int b = 1; b <= a; b ++)for column for column      {      是System.out.print( “*”);      }

System.out.println();}
}

public static void rightTriangle()
{
    // here 1st print space and then print star
  for (int a=1;a<=4;a++)// for loop for row
 { 
 for (int c =3;c>=a;c--)// for loop for space
 {  
 System.out.print(" ");
 }
 for (int d=1;d<=a;d++)// for loop for column
 { 
 System.out.print("*");   
 }
 System.out.println(); 
 }
 }

public static void centerTriangle()
{   
for (int a=1;a<=4;a++)// for lop for row
{   
for (int c =4;c>=a;c--)// for loop for space
{  
System.out.print(" ");
}
for (int b=1;b<=a;b++)// for loop for column
{
System.out.print("*"+" ");
}
System.out.println();}
}
public static void main (String args [])
{
space4 s=new space4();
s.leftTriangle();
s.rightTriangle();
s.centerTriangle();
}
}

答案 3 :(得分:2)

package apple;

public class Triangle
{
private static final int row = 3;

public static void main(String...strings){
    printLeftTrangle();
    System.out.println();
    printRightTrangle();
    System.out.println();
    printTrangle();
}

/*  Pattern will be
     *
     **
     ***
     ****
 */

public static void printLeftTrangle(){

    for(int y=1;y<=row;y++){
     for(int x=1;x<=y;x++)
         System.out.print("*");
     System.out.println();
    }
}

/*  Pattern will be
        *
       **
      ***
     ****
 */
public static void printRightTrangle(){
    for(int y=1;y<=row;y++){
        for(int space=row;space>y;space--)
            System.out.print(" ");
        for(int x=1;x<=y;x++)
            System.out.print("*");
        System.out.println();
    }
}

/*  Pattern will be
     *
    ***
   *****
*/

public static void printTrangle(){

    for(int y=1, star=1;y<=row;y++,star +=2){
        for(int space=row;space>y;space--)
            System.out.print(" ");
        for(int x=1;x<=star;x++)
            System.out.print("*");
        System.out.println();
    }
}
}

答案 4 :(得分:1)

对于右三角形,每行:

  • 首先:您需要打印从0到rowNumber - 1 - i的空格。
  • 第二:您需要从\*打印rowNumber - 1 - irowNumber

注意: i是从0到rowNumber的行索引,rowNumber是行数。

对于中心三角形:它看起来像“直角三角形”加上根据行索引添加\*(例如:在第一行中你不会添加任何东西,因为索引是0,在第二行你会添加一个'*',依此类推。)

答案 5 :(得分:1)

我知道这已经很晚了,但我想分享我的解决方案。

public static void main(String[] args) {
    String whatToPrint = "aword";
    int strLen = whatToPrint.length(); //var used for auto adjusting the padding
    int floors = 8;
    for (int f = 1, h = strLen * floors; f < floors * 2; f += 2, h -= strLen) {
        for (int k = 1; k < h; k++) {
                System.out.print(" ");//padding
            }
        for (int g = 0; g < f; g++) {
            System.out.print(whatToPrint);
        }
        System.out.println();
    }
}

三角形左侧的空格会根据您要打印的字符或字词自动调整。

如果whatToPrint = "x"floors = 3将打印

x xxx xxxxx 如果没有自动调整空格,它将如下所示(whatToPrint = "xxx"同一楼层数)

xxx xxxxxxxxx xxxxxxxxxxxxxxx

所以我添加了一个简单的代码,以便它不会发生。

对于左半部三角形,只需将strLen * floors更改为strLen * (floors * 2),将f +=2更改为f++

对于右半部三角形,只需移除此循环for (int k = 1; k < h; k++)或将h更改为0,如果您选择将其删除,请不要删除System.out.print(" ");

答案 6 :(得分:1)

//这适用于普通三角形

for (int i = 0; i < 5; i++)
        {
            for (int j = 5; j > i; j--)
            {
                System.out.print(" ");
            }
            for (int k = 1; k <= i + 1; k++) {
                System.out.print(" *");
            }
            System.out.print("\n");
        }

//这是左三角形,只是在打印前删除了空格*

for (int i = 0; i < 5; i++)
        {
            for (int j = 5; j > i; j--)
            {
                System.out.print(" ");
            }
            for (int k = 1; k <= i + 1; k++) {
                System.out.print("*");
            }
            System.out.print("\n");
        }

答案 7 :(得分:1)

1)正常三角形

package test1;


 class Test1 {

     public static void main(String args[])
     {
         int n=5;
     for(int i=0;i<n;i++)
     {

         for(int j=0;j<=n-i;j++)
         {

             System.out.print(" ");
         }

         for(int k=0;k<=2*i;k++)
         {
         System.out.print("*");
         }

         System.out.println("\n");

     }

     }

2)直角三角形

package test1;


 class Test1 {

     public static void main(String args[])
     {
         int n=5;
     for(int i=0;i<n;i++)
     {

         for(int j=0;j<=n-i;j++)
         {

             System.out.print(" ");
         }

         for(int k=0;k<=i;k++)
         {
         System.out.print("*");
         }

         System.out.println("\n");

     }

     }


}

     }

3)左角三角

package test1;


 class Test1 {

     public static void main(String args[])
     {
         int n=5;
     for(int i=0;i<n;i++)
     {

         for(int j=0;j<=i;j++)
         {

             System.out.print("*");
         }

         System.out.println("\n");

     }

     }


}

答案 8 :(得分:0)

    for(int i=1;i<=5;i++)
    {
        for(int j=5;j>=i;j--)
        {
            System.out.print(" ");
        }
        for(int j=1;j<=i;j++)
        {
            System.out.print("*");
        }

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

 *
***



答案 9 :(得分:0)

对于中心三角形

            *
          * * *

输出:

int a, b;
cin >> a >> b;
enum operation {add, sub, mul, div};
        operation d;
        switch (d)
        {
        case add : cout << "addition of two numbers is: " << a + b << endl;
            break;
        case sub : cout << "subtraction of two numbers is " << a - b << endl;
            break;
        case mul : cout << "multiplication of the two numbers is " << a * b << endl;
            break;
        case div : cout << "division of the two numbers is " << a / b << endl;
        default: cout << "invalid parameters" << endl;
        }

答案 10 :(得分:0)

您可能也对此感兴趣

      Scanner sc = new Scanner(System.in);
      int n=sc.nextInt();
      int b=0;
      for(int i=n;i>=1;i--){
      if(i!=n){
      for(int k=1;k<=b;k++){
      System.out.print(" ");
        }
            }
       for(int j=i;j>=1;j--){
       System.out.print("*");
       if(i!=1){
       System.out.print(" ");
        }
            }
       System.out.println();
       b=b+2;
        }

输出:: 5

       * * * * * 
         * * * * 
           * * * 
             * * 
               *

答案 11 :(得分:0)

d

答案 12 :(得分:0)

找到以下内容,它将帮助您打印完整的三角形。

package com.raju.arrays;

public class CompleteTriange {

public static void main(String[] args) {
    int nuberOfRows = 10;
      for(int row = 0; row<nuberOfRows;row++){

          for(int leftspace =0;leftspace<(nuberOfRows-row);leftspace++){
              System.out.print(" ");
          }
          for(int star = 0;star<2*row+1;star++){
              System.out.print("*");
          }
          for(int rightSpace =0;rightSpace<(nuberOfRows-row);rightSpace++){
              System.out.print(" ");
          }
          System.out.println("");
      }

}

}

          *          
     ***         
    *****        
   *******       
  *********      
 ***********     
*************    

答案 13 :(得分:0)

对于左对齐的直角三角形,您可以在java中尝试这个简单的代码:

context.setVariable(KEY, "Some value");

答案 14 :(得分:0)

问题:

      *
     ***
    *****

答案:

    int i,a,j;
    i=5;
    while (i>=3)
    {
        a=1;
        while (a<=i)
        {

            System.out.print(" ");
            a++;
        }
        j=10;
        while (j/2>=i)
        {
            System.out.print("*");
            --j;
        }
        System.out.println("");
        i--;
    }   

享受!!

答案 15 :(得分:0)

这是最简单的程序,它只需要1个循环来打印三角形。这仅适用于中心三角形,但小调整也可以使其适用于其他三角形 -

import java.io.DataInputStream;

public class Triangle {
    public static void main(String a[]) throws Exception{
        DataInputStream in = new DataInputStream(System.in);

        int n = Integer.parseInt(in.readLine());
        String b = new String(new char[n]).replaceAll("\0", " ");
        String s = "*";
        for(int i=1; i<=n; i++){
            System.out.print(b);
            System.out.println(s);
            s += "**";
            b = b.substring(0, n-i);
            System.out.println();
        }
    }
}

答案 16 :(得分:0)

public static void main(String[] args) {

    System.out.print("Enter the number: ");
    Scanner userInput = new Scanner(System.in);
    int myNum = userInput.nextInt();
    userInput.close();

    System.out.println("Centered Triange");
    for (int i = 1; i <= myNum; i+=1) {//This tells how many lines to print (height)

        for (int k = 0; k < (myNum-i); k+=1) {//Prints spaces before the '*'
            System.out.print(" ");
        }

        for (int j = 0; j < i; j++) { //Prints a " " followed by '*'.   
            System.out.print(" *");
        }

        System.out.println(""); //Next Line     
    }

    System.out.println("Left Triange");
    for (int i = 1; i <= myNum; i+=1) {//This tells how many lines to print (height)

        for (int j = 0; j < i; j++) { //Prints the '*' first in each line then spaces.  
            System.out.print("* ");
        }

        System.out.println(""); //Next Line         
    }

    System.out.println("Right Triange");
    for (int i = 1; i <= myNum; i+=1) {//This tells how many lines to print (height)

        for (int k = 0; k < (myNum-i); k+=1) {//Prints spaces before the '*'
            System.out.print("  ");
        }

        for (int j = 0; j < i; j+=1) { //Prints the " " first in each line then a "*".  
            System.out.print(" *");
        }

        System.out.println(""); //Next Line         
    }

}

答案 17 :(得分:0)

import java.util.Scanner;

public class A {

    public void triagle_center(int max){//max means maximum star having
        int n=max/2;
        for(int m=0;m<((2*n)-1);m++){//for upper star
            System.out.print(" ");
        }
        System.out.println("*");

        for(int j=1;j<=n;j++){
            for(int i=1;i<=n-j; i++){
                System.out.print("  ");
            }
            for(int k=1;k<=2*j;k++){
            System.out.print("* ");
            }

            System.out.println();
        }


    }

    public void triagle_right(int max){
        for(int j=1;j<=max;j++){
            for(int i=1;i<=j; i++){
                System.out.print("* ");
            }

            System.out.println();
        }
    }

    public void triagle_left(int max){
        for(int j=1;j<=max;j++){
            for(int i=1;i<=max-j; i++){
                System.out.print("  ");
            }
            for(int k=1;k<=j; k++){
                System.out.print("* ");
            }

            System.out.println();
        }
    }

    public static void main(String args[]){
        A a=new A();
        Scanner input = new Scanner (System.in);
        System.out.println("Types of Triangles");
        System.out.println("\t1. Left");
        System.out.println("\t2. Right");
        System.out.println("\t3. Center");
        System.out.print("Enter a number: ");
        int menu = input.nextInt();
        Scanner input1 = new Scanner (System.in);
        System.out.print("maximum Stars in last row: ");
        int row = input1.nextInt();
        if (menu == 1)
            a.triagle_left(row);
        if (menu == 2)
            a.triagle_right(row);
        if (menu == 3)
            a.triagle_center(row);
    }
}

答案 18 :(得分:0)

这将以三角形打印星星:

`   
public class printstar{
public static void main (String args[]){
int m = 0;
for(int i=1;i<=4;i++){
for(int j=1;j<=4-i;j++){
System.out.print("");}

for (int n=0;n<=i+m;n++){
if (n%2==0){
System.out.print("*");}
else {System.out.print(" ");}
}
m = m+1;
System.out.println("");
}
}
}'

阅读和理解这应该有助于你下次设计逻辑..

答案 19 :(得分:0)

对于三角形,你需要有三个循环代替两个, 一个外部循环迭代行号 主循环内部有两个并行循环 第一个循环打印减少循环次数 第二个循环打印增加'' 好吧,我也可以给出确切的逻辑,但如果你先试试它会更好 只需要集中每行中需要多少空格和多少'' 将符号的数量与循环迭代的行数相关联 你完成了 .....如果它更麻烦,请告诉我,我将用逻辑和代码解释

答案 20 :(得分:-1)

(a)   (b)        (c)   (d)
* ********** ********** *
** ********* ********* **
*** ******** ******** ***
**** ******* ******* ****
***** ****** ****** *****
****** ***** ***** ******
******* **** **** *******
******** *** *** ********
********* ** ** *********
********** * * **********

int line;
int star;
System.out.println("Triangle a");
        for( line = 1; line <= 10; line++ )
        {
            for( star = 1; star <= line; star++ )
            {

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

 System.out.println("Triangle b");

          for( line = 1; line <= 10; line++ )
        {
            for( star = 1; star <= 10; star++ )
            {

        if(line<star)
                System.out.print( "*" );
                else
                  System.out.print(" ");
            }
            System.out.println();
        }

 System.out.println("Triangle c");

          for( line = 1; line <= 10; line++ )
        {
            for( star = 1; star <= 10; star++ )
            {

        if(line<=star)
                System.out.print( "*" );
                //else
                 // System.out.print(" ");
            }
            System.out.println();
        }

 System.out.println("Triangle d");

          for( line = 1; line <= 10; line++ )
        {
            for( star = 1; star <= 10; star++ )
            {

        if(line>10-star)
                System.out.print( "*" );
                else
                  System.out.print(" ");
            }
            System.out.println();
        }