How do I use a void method without printing? - java

I am having problems understanding a program I need to write for class. My program works as it should, but the problem states that it wants me to not print within my methods. I am confused on how I should output my values because my methods must be void according to the problem (which doesn't return anything) and I can't print inside of them.
Here is the question:
Design and implement a java program (name it ArrayMethods), that defines 4 methods as follows:
int arrayMax (int[] array)
int arrayMin (int[] array)
void arraySquared (int[] array)
void arrayReverse (int[] array)
Test your methods by creating an array of length 5 within your main method and filling it with random numbers between 1 and 1000. Your program should then display the original array, display the smallest number in the array, display the greatest number in the array, display the revered array, and display the square of each value in the array. You main method shoudl invoke each method exactly once, with each invocation use the original array as the actual parameter. No printing within the methods. Document your code, and organize/space your outputs properly. Use escape characters and formatting objects when applicable.
So again my question is: How do I use those methods without printing anything if I can't return a value? If anyone could give me a clue on how to solve this, it would be greatly appreciated.
import java.util.Random;
import java.util.Arrays;
public class ArrayMethods
{
public static void main (String[] args)
{
int[] array = new int[5];
array[0] = (int)(Math.random() * (1000 - 1)) + 1;
array[1] = (int)(Math.random() * (1000 - 1)) + 1;
array[2] = (int)(Math.random() * (1000 - 1)) + 1;
array[3] = (int)(Math.random() * (1000 - 1)) + 1;
array[4] = (int)(Math.random() * (1000 - 1)) + 1;
System.out.println("The values within the array are: " + Arrays.toString(array));
System.out.println("The maximum value within the array is: " + arrayMax(array));
System.out.println("The minimum value of the array is: " + arrayMin(array));
System.out.print("The values within the array (squared) are: ");
arraySquared(array);
System.out.print("\n");
System.out.print("The array reversed is: ");
arrayReverse(array);
}
public static int arrayMax (int[] array)
{
int max = 0;
for (int i = 0; i < array.length; i++)
{
if (array[i] > max)
{
max = array[i];
}
}
return max;
}
public static int arrayMin (int[] array)
{
int min = 1000;
for (int i = 0; i < array.length; i++)
{
if (array[i] < min)
{
min = array[i];
}
}
return min;
}
public static void arraySquared (int[] array)
{
int[] array2 = new int[5];
for (int i = 0; i < array.length; i++)
{
array2[i] = array[i] * array[i];
System.out.print(array2[i]);
while ( i < array.length - 1)
{
System.out.print(", ");
break;
}
}
}
public static void arrayReverse (int[] array)
{
for(int i = array.length - 1; i >= 0; i--)
{
System.out.print(array[i] + " ");
}
}
}

For the void functions, in C# you'd simply use an "out" or "ref" keyword. If they insist on Java, Java doesn't have an equivalent, but you can do something like that with an object.
public class PassArray
{
public int[] array;
public PassArray(int[] array)
{
this.array = array;
}
}
public static void Reverse(PassArray arrayHolder)
{
int[] reversed = new int[arrayHolder.array.Length];
int j = 0;
for (int i = arrayHolder.array.Length - 1; i >= 0; i--)
{
reversed[j] = arrayHolder.array[i];
j++;
}
arrayHolder.array = reversed;
}
static void Main(string[] args)
{
int[] toReverse = new[] { 10, 30, 2, 1, 3, 100, 340 };
PassArray passedObject = new PassArray(toReverse);
Reverse(passedObject);
// passedObject.array will now have the reversed array
}
Obviously this could can be improved but it should at least give the right idea.

Related

Is there a way to sum up all numbers from an array in one method with a different method?

I have a brief idea as to how to add all the numbers in that array in the same method but I am not sure how to use a separate method to add all the numbers. The print2DArray() prints the array with the random numbers out in a 4x4 format. I can't figure out a way to make the method findSum() add up all the numbers in the method print2DArray().
public class randomBoard2 {
public static void main(String[] args) {
findSum(); //I was experimenting with this to see what worked
}
//method that prints out the array with random numbers are below
public static void print2DArray(){
int[][] a = new int [4][4];
for(int i = 0; i < a.length; i++) {
for(int j = 0; j < a[i].length; j++)
a[i][j] = (int)(Math.random() * 10);
}
for(int[] nums: a) {
for(int b: nums) {
System.out.print(b + " ");
}
System.out.println("");
}
}
//method that adds up all the numbers in the array above is below
public static void findSum() {
int sum = 0;
//The "a" in the for-each loop below is wrong. I'm not sure what to put in there instead.
for(int[] number: a) {
for(int d: number)
sum += d;
System.out.println("The sum of all the numbers is: " + sum);
}
}
}
I am relatively new to Java so I'm not sure how exactly I should make a method that adds all the numbers in another method. (I apologize in advance for the poor question phrasing).
To calculate the sum of 2D array (named 'a') and print it, try the following code:
int sum = 0;
for (int[] array : a) {
sum += IntStream.of(array).sum();
}
System.out.println(sum);
package com.test;
import java.util.Scanner;
/**
*
*
*
*
*
*
* #author shikai.liu
* #version 1.0
* #since JDK1.7
*/
public class TestList {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
print2DArray();
}
public static void print2DArray() {
int sum = 0;
int[][] a = new int[4][4];
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++)
a[i][j] = (int) (Math.random() * 10);
}
for (int[] nums : a) {
for (int b : nums) {
sum += b;
System.out.print(b + " ");
}
System.out.println("");
}
System.out.println(sum);
}
}

Use multiple methods in Java

How to use multiple methods in a code? First it asks for the size of an array, then for the numbers of the element. One method is rounding numbers with a special rule.
Second method is a void method which modifies the array. Third method is making a new array with the modified values and returns to this array.
package tombtombbekerekit;
import java.util.Scanner;
public class TombTombbeKerekit {
public static int round(int osszeg)
{
int last_Digit = osszeg % 10;
if(last_Digit < 3)
return osszeg - last_Digit;
else if(last_Digit > 7)
return osszeg + (10 - last_Digit);
else
return osszeg - (last_Digit) + 5;
}
public static void roundSelf(int [] numbers)
{
int[] array = numbers;
for (int i = 0; i < array.length; i++)
return;
}
public static int [] roundNew(int [] numbers)
{
int [] newArray = new int[numbers.length];
return newArray;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Kérem az összegek számát: ");
int size = sc.nextInt();
System.out.println("Kérem az összegeket: ");
int [] array = new int[size];
for (int i = 0; i < array.length; i ++)
{
array[i] = sc.nextInt();
}
int [] kerek = roundNew(array);
System.out.println("Kerekítve: ");
for (int i = 0; i < kerek.length; i++)
System.out.println(kerek[i]);
}
}
You should write your own function. Just find the rule for the rounding. You can use n%10 to get the last digit of an integer named n.
I've written something but haven't tested it, I believe it should work. Check it out:
public int weirdRounding(int n)
{
int last_Digit = n % 10;
if(last_Digit < 3)
return n - last_Digit;
else if(last_Digit > 7)
return n + (10 - last_Digit);
else // the last digit is 3,4,5,6,7
return n - (last_Digit) + 5;
}
Note: You should probably make this code more readable if you're going to use it. For example define int LOWER_BOUND = 3 and int UPPER_BOUND = 7 instead of using '3' and '7', you could also wrap the ugly expressions with functions (e.g. roundUp, roundToFive ..). #Magic_Numbers_Are_Bad

Need a sort method in Java with user input using the scanner class [duplicate]

This question already has answers here:
Need Java array help using scanner class to output an average and sort method
(4 answers)
Closed 6 years ago.
I have a method to output the highest value, lowest value, average value and I need a sort method. I have tried to put what is called a "bubble method" but it isn't working out. Anyone know other sort methods I can use?
import java.util.Scanner;
public class Arrayassignment {
public static void main(String[] args) {
Scanner sin = new Scanner(System.in);
System.out.println("Enter an intiger for array size.");
int number = sin.nextInt();
int array[] = new int[number];
System.out.println("Array size " + number + " initiated.\n");
System.out.println("Now enter the array intigers.");
for (int i = 0; i < number; i++) {
array[i] = sin.nextInt();
}
//System.out.println ( "\nLargest " + max (1, 3, 5) );
System.out.println("sorting" + sort(array));
System.out.println("The highest number in the array is " + max(array));
System.out.println("The smallest number in the array is " + min(array));
System.out.println("The average of the numbers in the array is " + avg(array));
}
public static int sort(int[] arg) {
for (int i = 1; i < arg.length - 1; i++) {
for (int j = i + 1; j < arg.length; j++) {
if (arg[i] > arg[j]) {
int arrange = arg[i];
arg[i] = arg[j];
arg[j] = arrange;
}
}
}
return arrange;
}
public static int max(int[] arg) {
if (arg.length == 0) {
System.out.println(" empty arguement list ");
return 0;
}
int largest = arg[0];
for (int i = 1; i < arg.length; i++) {
if (arg[i] > largest) {
largest = arg[i];
}
}
return largest;
}
public static int min(int[] arg) {
if (arg.length == 0) {
System.out.println(" empty arguement list ");
return 0;
}
int smallest = arg[0];
for (int i = 1; i < arg.length; i++) {
if (arg[i] < smallest) {
smallest = arg[i];
}
}
return smallest;
}
public static double avg(int... arr) {
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
double average = (double) sum / arr.length;
return average;
}
}
There are many other sort methods you can use. The one you were trying to use is called "Bubble Sort" and is very expensive on large data sets unless they are somewhat ordered. I would recommend using selection sort or insertion sort for what you are trying to accomplish.
Here is a link to the many sorting algorithms you can implement: Sorting Algorithms
Here are some animations showing the process of these sorts (Highly recommend you look at these before implementing your algorithm):
Helpful animations
You can use any sorting method as your convenient and according to your requirement. After sorted the array you can easily pick up the minimum and maximum value from the sorted array, first element and the last element of the array.
For calculate the average you have to use separate method as you used or you can use static variable to calculate the total inside the sorting method.
Refer this code.
public class Arrayassignment {
public static void main(String[] args) {
Scanner sin = new Scanner(System.in);
System.out.println("Enter an intiger for array size.");
int number = sin.nextInt();
int array[] = new int[number];
System.out.println("Array size " + number + " initiated.\n");
System.out.println("Now enter the array intigers.");
for (int i = 0; i < number; i++) {
array[i] = sin.nextInt();
}
sin.close();
System.out.println("sorting");
printArray(array); //Before sort
sort(array);
printArray(array); //After sort
System.out.println("The highest number in the array is " + array[array.length - 1]);
System.out.println("The smallest number in the array is " + array[0]);
System.out.println("The average of the numbers in the array is " + avg(array));
}
public static void sort(int[] arg) {
int arrange;
for (int i = 0; i < arg.length - 1; i++)
for (int j = i + 1; j < arg.length; j++) {
if (arg[i] > arg[j]) {
arrange = arg[i];
arg[i] = arg[j];
arg[j] = arrange;
}
}
}
public static double avg(int... arr) {
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
double average = (double) sum / arr.length;
return average;
}
public static void printArray(int[] arr) {
for (int value : arr) {
// print elements according to your convenient
System.out.println(value);
}
}
To print the array you have traversal through the array. See Above code method.

return values to main method

Ok this is making my brain melt!! the code compiles just fine but it refuses to display the correct answers in the displayAllResults method. Im not sure how to fix this at all. Ive tried making the methods private as well as having them return values instead of being void. as an example, the method sum gets the sum of the elements in array but will not display them. Im getting 0.
//Main
public class Lab_4_Practice {
public static void main(String[] args) {
//Declaring and initializing variables
int[] randomArray = new int[10];
int maxIndex = 0;
int minIndex = 0;
int total = 0;
double average = (total / randomArray.length);
//Call Methods
random(randomArray);
displayRandom(randomArray);
largest(maxIndex, randomArray);
smallest(minIndex, randomArray);
sum(total, randomArray);
average(total, randomArray);
sortArray(randomArray);
displaySorted(randomArray);
displayAllResults(randomArray, maxIndex, minIndex, total, average);
}
//***************************************************
//Method assigns random values to elements
public static void random(int[] randomArray) {
for (int i = 0; i <randomArray.length; i++) {
randomArray[i] = (int)(Math.random() * 300);
}
}
//Method prints random values
public static void displayRandom(int[] randomArray) {
System.out.println("Here are 10 random numbers");
for (int i = 0; i < randomArray.length; i++) {
System.out.println(randomArray[i]);
}
System.out.println("*************************");
}
//Method identifies largest index and its element in array
public static void largest(int maxIndex, int[] randomArray) {
for (int l = 1; l < randomArray.length; l++) {
if (randomArray[l] > randomArray[maxIndex]) {
maxIndex = l;
}
}
}
//Method identifies smallest index and its element in array
public static void smallest(int minIndex, int[] randomArray) {
for (int i = 1; i < randomArray.length; i++) {
if (randomArray[i] < randomArray[minIndex]) {
minIndex = i;
}
}
}
//Method calculates sum of elements
public static int sum(int total, int[] randomArray) {
for (int i = 0; i <randomArray.length; i++) {
total = total + randomArray[i];
}
return total;
}
//Method calculates average of elements
public static void average(int total, int[] randomArray) {
for (int i = 0; i < randomArray.length; i++) {
i += randomArray[i];
}
}
//Method sorts array in ascending order
public static void sortArray(int[] randomArray) {
for (int i = 0; i < randomArray.length - 1; i++) {
int currentMin = randomArray[i];
int currentMinIndex = i;
for (int j = i + 1; j < randomArray.length; j++) {
if (currentMin > randomArray[j]) {
currentMin = randomArray[j];
currentMinIndex = j;
}
}
if (currentMinIndex != i) {
randomArray[currentMinIndex] = randomArray[i];
randomArray[i] = currentMin;
}
}
}
//Method prints array in ascending order
public static void displaySorted(int[] randomArray) {
System.out.println("These are the same numbers sorted in ascending order");
for (int i = 0; i < randomArray.length; i++) {
System.out.println(randomArray[i] + " ");
}
System.out.println("*************************");
}
//Method prints results of largest smallest sum and average
public static void displayAllResults(int[] randomArray, int maxIndex, int minIndex, int total, double average) {
System.out.println("The largest index is " + maxIndex + " and its value is " + randomArray[maxIndex]);
System.out.println("The smallest index is " + minIndex + " and its value is " + randomArray[minIndex]);
System.out.println("The sum of the elements is " + total);
System.out.println("The average of the elements is " + average);
}
}
Its always recommended that you do all your calculations/manipulations in a different class rather than in the main class itself. Create a different class and inside that code something like this -
public class Example{
public void assign(int[] Array){
for(int i=0;i<Array.length;i++){
Array[i]=(int)(Math.random()*300);
}
}
public void display(int[] Array){
System.out.println("The 10 elements of the array are:");
for(int i=0;i<Array.length;i++){
System.out.println(Array[i]);
}
}
public int sum(int[] Array) {
int total =0;
for(int i=0;i<Array.length;i++){
total=total+Array[i];
}
return total;
}
//write all other methods here in this class.
}
now in the main class inside the main method just declare the array and pass the array to the different functions as per your requirement, something like this -
public static void main(String[] args) {
int[] randomArray=new int[10];
Example e=new Example();
e.assign(randomArray);//this must be called first to assign the values inside the array.
e.display(randomArray);//call this method if you wish to display the values.
System.out.println("The sum of the elements are: "+e.sum(randomArray));
}
I have done little bit changes in your code. You can compare it with your old code. Most of the places you were facing problem because of local variable. Whatever you were supplying to corresponding method and after operation changes made on local variable is not affecting your instance variables. And for largest() and small() method(), you were calling it without sorting your array, because of that it was giving wrong output.
public class StackProblem {
public static void main(String[] args) {
// Declaring and initializing variables
int[] randomArray = new int[10];
int maxIndex = 0;
int minIndex = 0;
int total = 0;
double average = 0;
// Call Methods
random(randomArray);
displayRandom(randomArray);
sortArray(randomArray);
maxIndex=largest(randomArray);
minIndex=smallest(randomArray);
total=sum(randomArray);
average=average(total, randomArray);
displaySorted(randomArray);
displayAllResults(randomArray, maxIndex, minIndex, total, average);
}
// ***************************************************
// Method assigns random values to elements
public static void random(int[] randomArray) {
for (int i = 0; i < randomArray.length; i++) {
randomArray[i] = (int) (Math.random() * 300);
}
}
// Method prints random values
public static void displayRandom(int[] randomArray) {
System.out.println("Here are 10 random numbers");
for (int i = 0; i < randomArray.length; i++) {
System.out.println(randomArray[i]);
}
System.out.println("*************************");
}
// Method identifies largest index and its element in array
public static int largest(int[] randomArray) {
int maxIndex=0;
for (int l = 0; l < randomArray.length; l++) {
if (randomArray[l] > randomArray[maxIndex]) {
maxIndex = l;
}
}
return maxIndex;
}
// Method identifies smallest index and its element in array
public static int smallest(int[] randomArray) {
int minIndex=0;
for (int i = 0; i < randomArray.length; i++) {
if (randomArray[i] < randomArray[minIndex]) {
minIndex = i;
}
}
return minIndex;
}
// Method calculates sum of elements
public static int sum(int[] randomArray) {
int localTotal=0;
for (int i = 0; i < randomArray.length; i++) {
localTotal+=randomArray[i];
}
return localTotal;
}
// Method calculates average of elements
public static int average(int total, int[] randomArray) {
return total/randomArray.length;
}
// Method sorts array in ascending order
public static void sortArray(int[] randomArray) {
for (int i = 0; i < randomArray.length - 1; i++) {
int currentMin = randomArray[i];
int currentMinIndex = i;
for (int j = i + 1; j < randomArray.length; j++) {
if (currentMin > randomArray[j]) {
currentMin = randomArray[j];
currentMinIndex = j;
}
}
if (currentMinIndex != i) {
randomArray[currentMinIndex] = randomArray[i];
randomArray[i] = currentMin;
}
}
}
// Method prints array in ascending order
public static void displaySorted(int[] randomArray) {
System.out.println("These are the same numbers sorted in ascending order");
for (int i = 0; i < randomArray.length; i++) {
System.out.println(randomArray[i] + " ");
}
System.out.println("*************************");
}
// Method prints results of largest smallest sum and average
public static void displayAllResults(int[] randomArray, int maxIndex, int minIndex, int total, double average) {
System.out.println("The largest index is " + maxIndex + " and its value is " + randomArray[maxIndex]);
System.out.println("The smallest index is " + minIndex + " and its value is " + randomArray[minIndex]);
System.out.println("The sum of the elements is " + total);
System.out.println("The average of the elements is " + average);
}
[Nobody supports my motion to put this on hold due to [duplicate] - so I feel compelled to write an answer here.]
This is the typical pattern for a method calculating some value from the elements of an array:
public static int largest(int[] array) {
int maxIndex = 0;
for (int l = 1; l < array.length; l++) {
if (array[l] > array[maxIndex]) {
maxIndex = l;
}
}
return maxIndex;
}
And you call it like this:
int maxIndex = largest( randomArray );
Parameters with a type of int, long, double, char, short, float, boolean are copied "by value", i.e., the corresponding expression in the call - the actual parameter - is evaluated and the result is stored in a variable with the name of the parameter. This variable is short-lived: when you return from the method call, it is gone. The only way to hand back the value is by using the return mechanism in a non-void method.
If you have an array however, things are a little different. An array is an object, and objects are handled via references, values that tell the computer where the object can be found. This reference is also copied from the point of invocation and stored in a short-lived variable, but you still can access the object it references so that changes of an array (or any object) are possible via code in a method with an object reference as a parameter.
Finally, the code for calculating the average is very much in error.
public static double average( int[] array ) {
return (double)sum( array )/array.length;
}
and you need a variable of type double to hold the result. (There is a chance that an array might have the length 0, so I'm a little careless there. Do you see why?)
The variables you are passing to each method are all zero. You need to change those within the main method, since variables in methods are only used and modified within their respective methods, even if they were passed to that method from the main method. It looks like this is what you want:
randomArray = random(randomArray);
displayRandom(randomArray);
maxIndex = largest(maxIndex, randomArray);
minIndex = smallest(minIndex, randomArray);
total = sum(total, randomArray);
average(total, randomArray); //not sure what you're trying to do here; this method does not calculate the average
average = total/randomArray.length; //you probably just want to use this instead of the average() method
randomArray = sortArray(randomArray);
displaySorted(randomArray);
displayAllResults(randomArray, maxIndex, minIndex, total, average);
Additionally, for each method that is supposed to return a value, you will need to change the return type in the method header from void to the appropriate variable type, as well as add a return statement at the end of each method.

Recursive method for Pascal's triangle

I have written a method to evaluate a Pascal's triangle of n rows. However when I test the method I receive the error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
Here is the code:
public static int[] PascalTriangle(int n) {
int[] pt = new int[n + 1];
if (n == 0) {
pt[0] = 1;
return pt;
}
int[] ppt = PascalTriangle(n - 1);
pt[0] = pt[n] = 1;
for (int i = 0; i < ppt.length; i++) {
pt[i] = ppt[i - 1] + ppt[i];
}
return pt;
}
Please let me know if you have any ideas for how the code could be edited to fix the problem.
for(int i = 0; i < ppt.length; i++)
{
pt[i] = ppt[i-1] + ppt[i];
In your first iteration, i == 0 and so (i-1) == -1. This is the cause of the error.
You can special handle the boundaries to avoid this. Or as the others have suggested, start i at 1 instead of 0.
Here is some code a friend of mine came up with
import java.util.Scanner;
public class Pascal {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of rows to print: ");
int rows = scanner.nextInt();
System.out.println("Pascal Triangle:");
print(rows);
scanner.close();
}
public static void print(int n) {
for (int i = 0; i < n; i++) {
for (int k = 0; k < n - i; k++) {
System.out.print(" "); // print space for triangle like structure
}
for (int j = 0; j <= i; j++) {
System.out.print(pascal(i, j) + " ");
}
System.out.println();
}
}
public static int pascal(int i, int j) {
if (j == 0 || j == i) {
return 1;
} else {
return pascal(i - 1, j - 1) + pascal(i - 1, j);
}
}
}
In this code:
pt[0] = pt[n] = 1;
for(int i = 0; i < ppt.length; i++)
{
pt[i] = ppt[i-1] + ppt[i];
}
the problem is that when i is 0, you're trying to access ppt[i-1] which is ppt[-1]. The thing to notice is that when i is 0, you don't need to execute the statement that sets pt[i], because you already set pt[0] up before the loop! Try initializing i to 1 instead of 0.
Improvement in #Clemson code using Dynamic Programming :
class Solution {
int[][] dp ;
public List<List<Integer>> generate(int numRows) {
dp = new int[numRows][numRows];
List<List<Integer>> results = new ArrayList<>();
pascal(results, numRows);
return results;
}
private void pascal(List<List<Integer>> results, int numRows) {
for(int i = 0; i < numRows; i++) {
List<Integer> list = new ArrayList<>();
for(int j = 0; j <= i ; j++) {
list.add(dfs(i, j));
}
results.add(list);
}
}
private int dfs(int i, int j) {
if(j == 0 || i == j) return 1;
if(dp[i][j] != 0) return dp[i][j];
return dp[i][j] = dfs(i - 1, j - 1) + dfs(i - 1, j );
}
}
This isn't the solution to your code but it is solution to printing Pascals Triangle using only recursion which means no loops, using the combinations formula. All it needs is a main method or demo class to create an instance of the PascalsTriangle class. Hope this helps future Java students.
public class PascalsTriangle {
private StringBuilder str; // StringBuilder to display triangle
/**
* Starts the process of printing the Pascals Triangle
* #param rows Number of rows to print
*/
public PascalsTriangle(int rows) {
str = new StringBuilder();
printTriangle(rows, str);
}
/**
* Uses recursion to function as an "outer loop" and calls
* itself once for each row in triangle. Then displays the result
* #param row The number of the row to generate
* #param str StringBuilder to insert each row into
*/
public static void printTriangle(int row, StringBuilder str) {
// calls itself until row equals -1
if (row >= 0) {
// calls lower function to generate row and inserts the result into front of StringBuilder
str.insert(0, getRow(row, 0) + "\n");
// calls itself with a decremented row number
printTriangle(row - 1, str);
} else {
// when the base case is reached - display the result
JOptionPane.showMessageDialog(null, str);
System.exit(0);
}
}
/**
* Uses recursion to act as the "inner loop" and calculate each number in the given row
* #param rowNumber Number of the row being generated
* #param elementNumber Number of the element within the row (always starts with 0)
* #return String containing full row of numbers or empty string when base case is reached
*/
public static String getRow(int rowNumber, int elementNumber) {
// calls itself until elementNumber is greater than rowNumber
if (elementNumber <= rowNumber) {
// calculates element using combinations formula: n!/r!(n-r)!
int element = fact(rowNumber) / (fact(elementNumber) * (fact(rowNumber - elementNumber)));
// calls itself for each element in row and returns full String
return element + " " + getRow(rowNumber, elementNumber + 1);
} else return "";
}
/**
* Helper function that uses recursion to calculate factorial of given integer
* #param n Number to calculate factorial
* #return Factorial
*/
public static int fact(int n) {
if (n <= 0)
return 1;
else
return n * fact(n - 1);
}

Categories