我剛開始學習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語句的突破。有人可以告訴我爲什麼這樣做,以及如何解決這個問題?
你如何比較java中的字符串? – silentprogrammer
打印答案以檢查其值。同時修復(keepGoing = true)。 – jarmod