2017-09-24 202 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")) {