简体   繁体   English

数字总和模式java

[英]Numbers sum pattern java

Hello I need to create this pattern in java你好我需要在java中创建这个模式

图案

Im new to this and Im trying different codes but cant find out how to do it.Ive tried this one我是新手,我尝试了不同的代码,但不知道怎么做。我试过这个

 public class JavaProgram
 {
 public static void main(String args[])
  {
    int i, j, num;
    for(i=1; i<=5; i++)
    {
        num=1;
        for(j=1; j<=i; j++)
        {
            System.out.print(num+ " ");
            num++;
        }
        System.out.println();
    }
}}

But the result of this one is但是这个结果是

这个

Any help?有什么帮助吗?

This solution you'll find quite easier than other answers here :)这个解决方案你会发现比这里的其他答案更容易:)

import java.util.Scanner;
public class Main {

    public static void main(String[] args) {
        // Write your code here
        Scanner s = new Scanner(System.in);
        int N = s.nextInt();
        int sum=0;
        for(int i=1;i<=N;i++){
            sum=0;
            for(int j=1;j<=i;j++){
                sum=sum+j;
                System.out.print(j);
                if(j<i)
                    System.out.print("+");
            }System.out.println("=" + sum);
        }
    }
}

Ok so after a few tries I found the correct code by myself.好的,经过几次尝试,我自己找到了正确的代码。 This is the solution.这就是解决方案。

public class JavaProgram
   {
    public static void main(String args[])
     {
    int i, j, num;
    for(i=1; i<=5; i++)
    {
        num=1;
        int sum=0;
        for(j=1; j<=i; j++)
        {

            System.out.print(num+ "");

            sum=sum+num;
            if (num<i) {
                System.out.print("+");
            }  
            num++;

        }

            System.out.print("="+sum);
        System.out.println();
    }
   }
}
public class Test
{
    public static void printStars(int n)
    {
        int i, j,temp = 0;

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

            }
            temp = temp + j - 1;
            if (temp>1) {
                System.out.print(temp + " ");
            }

            System.out.println();

        }
    }
    public static void main(String args[])
    {
        int n = 10;
        printStars(n);
    }

}

Using While loops使用 While 循环

public static void main(String[] args) {

        Scanner sc = new Scanner (System.in);

        int n = sc.nextInt();

        int row = 1;

        while(n>=row){

            int col = 1;
            int sum = 0;

            while (col<=row){

                sum += col;

                System.out.print(col);

                if(row>col)
                    System.out.print(" + ");

                col++;

                }
            System.out.println(" = " + sum);
            row++;

            }


}

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

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