Create a class, called TriangleNumbers, that has a static public method called g
ID: 3798183 • Letter: C
Question
Create a class, called TriangleNumbers, that has a static public method called genNum that takes one non-negative integer argument n, and returns the nth triangle number, an integer. The nth triangle number is defined as the sum of numbers 1 through n, inclusive. For example: First triangle number = 1 Third triangle number = 1 + 2 + 3 = 6 Ninth triangle number =1+2 + 3 + ... + 8 + 9 = 45 The program should prompt the user to enter an integer x (you can safely assume it is greater than 0), and then print the first x triangle numbers, with each j^th line holding the j^th triangle number amount of values, separated by commas (except for the last number in every line). So the first line would contain the first triangle number, the second line would contain the next three, the third line would contain the next six, the fourth line would contain the next ten, and so forth. Sample input/output: User enters 4, program outputs: 1 3, 6, 10 User enters 22, program outputs: 1 3, 6, 10 15, 21, 28, 36, 45, 55 66, 78, 91, 105, 120, 136, 153, 171, 190, 210 231, 253Explanation / Answer
package myProject;
import java.util.*;
//Class TriangleNumbers definition
public class TriangleNumbers
{
//Method returns total of numbers till n
int getNum(int n)
{
int tot = 0;
//Loops from 1 to n and calculates the sum
for(int x = 1; x <= n; x++)
tot += x;
//returns total
return tot;
}//end of method
//Main method
public static void main(String ss[])
{
//Variable declaration
int t = 1, p = 1, x = 1, y, c = 0;
//Scanner class object created to accept number of output
Scanner sc = new Scanner(System.in);
//Creates TriangleNumbers class object
TriangleNumbers tn = new TriangleNumbers();
//Accepts number of output needed
System.out.println("Enter how many outputs you need: ");
int no = sc.nextInt();
//Loops till number of output encountered
while(c < no)
{
//Loops 1 to number of terms
for(y = 1; y <= t; y++)
{
//Displays the value
System.out.print(tn.getNum(p++) + ", ");
//counter is increased
c++;
//If counter is equal to number of output then break
if(c == no)
break;
}
//Number of terms is sum of row number, number of previous iteration
t = y + x++;
//New line
System.out.println();
}//End of while
}//End of main method
}//End of class
Output:
Enter how many outputs you need:
22
1,
3, 6, 10,
15, 21, 28, 36, 45, 55,
66, 78, 91, 105, 120, 136, 153, 171, 190, 210,
231, 253,
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.