我在do-while循环中使用Scanner时遇到以下Java代码的问题。该代码应该计算用户请求的阶乘的值,然后询问用户他/她是否想要计算另一个阶乘。如果他们说是,那么循环再次运行,如果否,则循环退出。
在第一次迭代中,一切都顺利进行。但是,当它询问我是否要计算另一个数字时,虽然我输入"是"但它不会再次运行。我读了here,添加一个nextLine()来清除\ n可能会有所帮助,但我似乎无法让它工作 - 任何提示?
import java.util.*;
public class Factorial
{
public static void main(String[] args)
{
Scanner kbscanner = new Scanner(System.in);
String answer;
do
{
// get the value from the user
System.out.print("\nEnter a Number: ");
int number = kbscanner.nextInt();
// compute factorial
int factorial = 1;
for (int i = 1; i <= number; i++)
factorial *= i;
// display factorial
System.out.println("The value of " + number + "! is " + factorial);
// ask if user wants to calculate another factorial
System.out.print("Would you like to calculate another number? ");
kbscanner.nextLine(); // gets rid of the \n from when nextInt was asked
answer = kbscanner.next();
} while (answer == "Yes");
System.out.println("End");
}
}