简体   繁体   English

使用Java形成图案

[英]Pattern formation using Java

I am trying to print a pattern of numbers in inverted triangle using Java. 我正在尝试使用Java在倒三角形中打印数字模式。 I have tried many times by using different conditions but couldn't get exactly the same type of pattern. 我已经使用不同的条件尝试了很多次,但是无法获得完全相同类型的模式。 Sometimes the order of number gets changed or sometimes the number of spaces before the numbers gets changed. 有时数字的顺序被更改,或者有时数字被更改之前的空格数。 This is the basic structure of my code: 这是我的代码的基本结构:

import java.io.*;
import java.util.*;

class S
{
    public static void main (String args [])
    {
        int no = (int)(Math.random() * 10);
        for (int x = no; x >= 1; x--)
        {
            for (int y = no; y >= 1; y--)
            {
                if ()
                    System.out.print(y) ;
                else ()
                    System.out.print (" ");
            }
            System.out.println();
        }
    }
}

The expected result is: 预期结果是:

5 4 3 2 1
  5 4 3 2
    5 4 3
      5 4
        5

I can't get the proper condition that should come in if and else . 我不能让将要来的,如果其他合适的条件。 I tried many but can't get the following pattern as it is. 我尝试了很多,但无法获得以下模式。

How can we print pattern like this in Java 我们如何在Java中打印这样的模式

Can someone suggest what should come under the if and else coditions to get this pattern. 有人可以建议在if和else编码中应该包含什么才能得到这种模式。

You don't actually need any special conditions, you can answer your question just by using your loops. 实际上,您不需要任何特殊条件,只需使用循环即可回答您的问题。

for(int i=0; i< no; i++){
    for(int j=no; j>i; j--){
        System.out.print(j+ " ");
    }
    System.out.println();
}

This should give you the correct output, all you need to do now is your formatting. 这应该给您正确的输出,现在您要做的就是格式化。

check this::: just add a special integer i: 检查此:::只需添加一个特殊的整数i:

import java.io.*;
import java.util.*;

class S
{
public static void main (String args [])
{
    int no = (int)(Math.random() * 10);
    int i = 0;
    for (int x = no; x >= 1; x--)
    {
        for (int y = no; y >= 1; y--)
        {
            if (x > y){
                System.out.print((y+i)+" ") ;
            }
            else{
                System.out.print ("  ");
        }}
        System.out.println();
    i++;
    }
}
}

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

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