2015-09-19 72 views
-1

我剛開始學習Java,並且我爲什麼在代碼底部執行我的「break」命令時有點遺憾。(JAVA)Break命令在執行時不應該執行

import java.util.Scanner; 

public class GradeValues { 

    private static Scanner scanner; 

    public static void main(String[] args) { 
     boolean keepGoing = true; 
     String grade; // initializing variable for grade 

     while(keepGoing = true){ 
      System.out.println("What percentage did you get? "); //Ask User the question 
      scanner = new Scanner(System.in); //starting the scanner 
      grade = scanner.nextLine(); //storing user input of percentage 

      int percentage = Integer.parseInt(grade); //converting string to a int 

      if(percentage >= 80 && percentage <= 100){ 
       System.out.println("Your grade is an A! Awesome job!"); 
      }else if(percentage >= 70 && percentage <= 79){ 
       System.out.println("Your grade is an B! Nice work!"); 
      }else if(percentage >= 60 && percentage <= 69){ 
       System.out.println("Your grade is an C! That's average. =("); 
      }else if(percentage >= 50 && percentage <= 59){ 
       System.out.println("Your grade is an D! Come on man, you can do better."); 
      }else if(percentage < 50){ 
       System.out.println("Your grade is an F! You need to hit the books again and try again."); 
      }else{ 
       System.out.println("I think you type the wrong value."); 
      } 

      System.out.println("Would you like to check another grade?"); //Asking user if they want to do it again 
      Scanner choice = new Scanner(System.in); //Gets user input 
      String answer = choice.nextLine(); // Stores input in variable "answer" 
      if(answer == "yes"){ 
       keepGoing = true; //While loop should keep going 

      }else{ 
       keepGoing = false; //While loop should stop 
       break; //this should stop program 
      } 
     } 
    } 
} 

考慮到keepGoing布爾變量仍然是正確的(如果用戶鍵入「是」),該應用程序仍將停止,因爲else語句的突破。有人可以告訴我爲什麼這樣做,以及如何解決這個問題?

+2

你如何比較java中的字符串? – silentprogrammer

+0

打印答案以檢查其值。同時修復(keepGoing = true)。 – jarmod

回答

2

你不能比較兩個字符串用==操作符。

爲了正確比較字符串,您必須使用equals方法。

例如,在你的代碼替換if/else語句:

if("yes".equals(answer)){ 
    keepGoing = true; //While loop should keep going 

}else{ 
    keepGoing = false; //While loop should stop 
    break; //this should stop program 
} 
+0

這解決了我的問題。非常感謝! :) – Tscott

0

answer是一個字符串,它是一種對象類型。你應該把它與equals方法相比,不==操作:

if (answer.equals("yes")) { 
    // etc. 
+2

這是不正確的。當你有一個常數值時,最好的辦法是把這個參數作爲這個參數:'「yes」.equals(answer)'以便不在代碼中產生隨機的空指針。 –

+0

'answer'可以爲空,並且您將得到NPE – msangel

+0

@VoodooCoder'answer'永遠不會爲空。如果沒有下一行,'Scanner.nextLine'將引發異常。 – resueman

1

我想,如果它不是那麼錯字你而條件是不正確while(keepGoing = true) ......應該是while(keepGoing == true)while(keepGoing)。因此,你不需要中斷。和其他答案中的建議一樣,請使用equals來比較字符串。