为什么我的while循环条件不起作用?

时间:2017-09-24 22:17:25

标签: java

当我尝试使用while循环时,它不会遵循我在while中设置的条件。就像我放while s1 != "n")一样,即使s1 = n,它也会继续。当我尝试使用while s1 == "y")时,情况正好相反,而且非常恼人。我试图制作一个因子计算器,提示用户是否愿意继续前进或停止。

这里是完整的代码:

package factorial;

import java.util.Scanner;

public class Factorial {

    public static void main(String[] args) {
    int factorial = 1;
    int number = 6;
    int i = 1;
    String s1 = "y";

    Scanner keyboard = new Scanner(System.in);

while(s1 != "n") {
    System.out.println("Enter an N:");
    number = keyboard.nextInt();
    while(i <= number) {
        factorial *= i;
        i++;
    }
    System.out.println("Factorial = "+factorial);
    System.out.println("Would you like to continue? (y/n)");
    s1 = keyboard.next();
}
keyboard.close();
System.out.println("Have a nice day!");
}
}

1 个答案:

答案 0 :(得分:-1)

正如@Debabrata所说,对字符串使用equals,替换:

while(s1 != "n") {

while(!s1.equals("n")) {