2017-02-11 163 views
0

如果用戶輸入特定的輸入,我必須跳出循環。但我無法使用if循環來打破while循環。我也嘗試在while循環中使用相同的條件,但這也不起作用。無法擺脫while循環。

import java.util.Scanner; 

public class Main { 
    public static void main(String[] args) {  
     String quit; 
     Scanner c = new Scanner(System.in); 

     while (true) { 
      leapOrNot y = new leapOrNot(); 
      System.out.println("press x to stop or any other letter to continue"); 
      quit = c.next(); 
      if (quit == "x" || quit == "X") { 
       break; 
      } 
     } 
    } 
} 

class leapOrNot { 
    final String isLeap = " is a leap year."; 
    final String notLeap = " is not a leap year."; 
    int year; 
    public leapOrNot() { 
     Scanner a = new Scanner(System.in); 
     System.out.println("Enter a year after 1581: "); 
     year = a.nextInt(); 
     /* if (a.hasNextInt() == false) { 
      System.out.println("Enter a 4 digit integer: "); 
      year = a.nextInt(); 
     } 
     couldn't make this condition work either 
     */ 
     while (year < 1582) { 
      System.out.println("The year must be after 1581. Enter a year after 1581: "); 
      year = a.nextInt(); 
      continue; 
     } 

     if (year % 4 == 0) { 
      if(year % 400 == 0 && year % 100 == 0) { 
       System.out.println(year + isLeap); 
      } 
      if (year % 100 == 0) { 
       System.out.println(year + notLeap); 
      } 
      else { 
       System.out.println(year + isLeap); 
      } 
     } 
     else { 
      System.out.println(year + notLeap); 
     } 
    } 
} 
+0

提示:'c.next()toLowerCase()'將有助於降低你的平等 –

+0

不要使用''==或'='比較字符串!改爲使用「equals(...)」或「equalsIgnoreCase(...)」方法。理解'=='檢查兩個*對象引用*是否相同,而不是你感興趣的。另一方面,方法檢查兩個字符串是否具有相同順序的相同字符,這就是這裏很重要。 –

回答

0

你應該使用String.equals()。有以下兩種

  • if (quit.charAt(0) == 'x' || quit.charAt(0) == 'X')
  • if (quit.equals("x") || quit.equals("X"))

更換任何上述將正常工作。

或只使用if(quit.equalsIgnoreCase("x"))

+0

'equalsIgnoreCase'將是首選 –