1

I'm trying to use a while loop to keep on asking the user if they want a certain row of the pascal's triangle. I don't know where to put my while loop.

I want to ask Another(y/n)? and if the user puts in y I ask for Which line number of pascal's triangle?

and the entire thing goes again.

import java.util.Arrays;
import java.util.Scanner;

public class PascalTriangle
{ 
   public static void main(String[] args) 
   {  
   Scanner scanner = new Scanner(System.in);
   System.out.print("Which line number of pascal's triangle ? ");
   int rowToCompute = scanner.nextInt();   
   System.out.println("Line " + rowToCompute + " of Pascal's Triangle is " + Arrays.toString(computeRow(rowToCompute)));
   System.out.println("Another (y/n)?");
   String another = scanner.nextLine();

   while(another.equalsIgnoreCase("y"))
   {
      System.out.print("Which line number of pascal's triangle ? ");
   }
}

public static int[] computeRow(int rowToCompute)
{
  if(rowToCompute == 1) 
  {
    int[] arr1 = new int[1];    
      arr1[0] = 1;
    return arr1;
  }

  else
  {
     int[] lastRow = computeRow(rowToCompute - 1);
     int[] thisRow = computeNextRow(lastRow);

       return thisRow;
  }

}//ends computeRow method

public static int[] computeNextRow(int[] previousRow)
{
     int[] newAr = new int[previousRow.length + 1];

     newAr[0] = 1;
     newAr[previousRow.length] = 1;

     for(int i = 1; i < previousRow.length; i++)
     {
        newAr[i] = previousRow[i-1] + previousRow[i];
     }

      return newAr;
  }//ends computeNextRow method 

}//end pascal triangle class
Anonymous
  • 43
  • 1
  • 8
  • A common approach to solving problems like this one in linear (it is also applicable here) programming is to wrap your program loop in another loop. When you are done guessing, the inner loop, you will move on to the outer loop where you will be asked to do another round. – Emz Nov 21 '15 at 21:08

1 Answers1

0

You should try something like this.

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    while (true) { // infinity loop, because you want ask many times
        System.out.print("Which line number of pascal's triangle ? ");
        int rowToCompute = scanner.nextInt();
        System.out.println("Line " + rowToCompute + " of Pascal's Triangle is " + Arrays.toString(computeRow(rowToCompute)));

        System.out.println("Another (y/n)?");
        String another = scanner.next();

        if (!another.equalsIgnoreCase("y")) { // if answer is other then 'y', break the loop
            break;
        }
    }
}
Mateusz Korwel
  • 1,118
  • 1
  • 8
  • 14