2017-09-24 62 views
-1

当我尝试使用while循环时,它不会遵循我在此设置的条件。就好像我把while s1 != "n")它会继续,即使s1 = n。当我尝试使用while s1 == "y")时,情况正好相反,它非常刺激。我试图制作一个因子计算器,提示用户是否想要继续或停止。为什么我的while循环条件不起作用?

下面是完整的代码:

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!"); 
} 
} 
+2

它是',而(s1.equals! (“n”))'为字符串。 – Debabrata

回答

-1

由于@Debabrata说使用等于字符串,替换:

while(s1 != "n") { 

while(!s1.equals("n")) { 
相关问题