簡體   English   中英

使用 for 循環和 while 循環創建 2 個三角形

[英]Create 2 triangles using for loop and while loop

在此處輸入圖片說明

嘗試使用 for 和 while 循環打印出 2 個三角形,其中 n 是由用戶輸入的。
但是while循環我無法打印出三角形,它應該是這樣的:

n = 3
*X
*X X
*X X X
*X
*X X
*X X X

但它打印出來是這樣的

X
X X
X X X
X
X
X
X
X
X
import java.util.*;
public class Triangle
{
public static void main(String[] args)
{
    Scanner input = new Scanner(System.in);
    int n, number, count=0, count1;

    System.out.print("Please enter an integer number: ");
    n = input.nextInt();

    if (n>0)
    {
       for(int i = 1; i<=n; i++)
       {    
           for(int j=0; j<i;j++)
           System.out.print(" X");


           System.out.println("");


       }

       while(count<n)
       {   
           count = count +1;
           count1 = 0;
           while(count1 < count)
           {

               System.out.print(" X");
               System.out.println("");

               count1 = count1 + 1;
            }
       }


    }
    else
    {
    System.out.print("Invalid number! Enter the number again!");
    }

   }
   }

看看你的 while 循環。 你有System.out.println(""); 在你的內部 while 循環中。 就像在帶有 for 循環的版本中一樣, System.out.println(""); 應在處理完內部 while 循環后調用。

while(count<n) //outer
{   
    count = count +1;
    count1 = 0;
    while(count1 < count) //inner
    {
        System.out.print(" X");
        count1 = count1 + 1;
    }
    System.out.println(""); // Thats the right place. 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM