Home > Java > Javagetting Started > body text

Use java to input a Yang Hui triangle with a specified number of rows

王林
Release: 2020-08-29 15:56:06
forward
3095 people have browsed it

Use java to input a Yang Hui triangle with a specified number of rows

Yang Hui's triangle is arranged by numbers. It can be regarded as a digital table. Its basic characteristic is that the values ​​​​on both sides are 1, and the values ​​​​in other positions are the values ​​​​in the upper left and The sum of the values ​​in the upper right corner. When printing Yang Hui's triangle, you need to use a for loop statement.

(Video tutorial recommendation: java course)

The implementation idea of ​​printing Yang Hui's triangle is: there are spaces in front of each line, and the number of spaces in each line needs to be based on Determined by the total number of rows, this can be summarized by finding rules. The key is the implementation of the value. The value in each row (except the first and last columns) is the sum of the two values ​​in the previous row, so it can be obtained from the previous row.

The implementation steps are as follows:

(1) Create a class named Test28, declare the num() method in the class, and pass in two parameters in the num() method, namely x and y. where x represents the row and y represents the column. The num() method is used to calculate the value of row x and column y. The code is as follows:

Use java to input a Yang Hui triangle with a specified number of rows

#(2) Create a method named calculate, and pass in a parameter of type int in this method, which represents the number of rows to print Yang Hui's triangle. The code is as follows:

Use java to input a Yang Hui triangle with a specified number of rows

(Related tutorial recommendations: java introductory tutorial)

(3) Add code in the main() method , first receive the number of printing lines input by the user on the console, and then pass the number of lines as a parameter to the calculated() method called. The code is as follows:

Use java to input a Yang Hui triangle with a specified number of rows

#(4) Run the code to test, the running results are as follows:

Use java to input a Yang Hui triangle with a specified number of rows

The above is the detailed content of Use java to input a Yang Hui triangle with a specified number of rows. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:biancheng.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template