1
我試圖使用while循環來繼續詢問用戶他們是否想要pascal三角形的某一行。我不知道把我的while循環放在哪裏。試圖使用while循環來保持循環,直到用戶放入n(Java)
我想問另一個(y/n)?如果用戶輸入y,我會問哪個pascal三角形的行號?
整個事情再次發生。
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
在線性編程(這也適用於此)編程中解決類似問題的常見方法是將程序循環包裝到另一個循環中。當你完成猜測後,內部循環,你將進入外部循環,你將被要求做另一輪。 – Emz