gpt4 book ai didi

java - 尝试使用 while 循环继续循环,直到用户输入 n (Java)

转载 作者:太空宇宙 更新时间:2023-11-04 13:12:15 25 4
gpt4 key购买 nike

我正在尝试使用 while 循环来继续询问用户是否想要帕斯卡三角形的某一行。我不知道该把 while 循环放在哪里。

我想问另一个(y/n)?如果用户输入 y,我会询问帕斯卡三角形的第几行?

整个事情再次发生。

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

最佳答案

你应该尝试这样的事情。

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;
}
}
}

关于java - 尝试使用 while 循环继续循环,直到用户输入 n (Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33848501/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com