Java的while循环尽管条件为假也不终止。

huangapple go评论57阅读模式
英文:

Java while loop not terminating despite condition being false

问题

我想创建一个名为Crap的游戏。我遇到的问题是,尽管条件被设置为false(当用户在询问是否要继续玩时输入“no”),但主while循环不会结束。问题出在哪里?问题所在处我已经插入了注释。

import java.util.Scanner;

public class crap {

	public static void main(String[] args) {
		System.out.println("你即将玩一个叫做Crap的游戏。按Enter键继续。");
		
		Scanner enter = new Scanner(System.in);
		String hitEnter = enter.nextLine();
		Scanner input = new Scanner(System.in);
		String proceed = "yes";
	        
        // 即使 proceed == "no",这个循环也不会退出
		while (!proceed.equals("no")){
			
			int playerPoint;
			int firstDice = 1 + (int) (Math.random() * 10) % 6;
			int secondDice = 1 + (int) (Math.random() * 10) % 6;
			int throwSum = firstDice + secondDice;
			
			if (throwSum == 7 || throwSum == 11) {
				System.out.println("恭喜!你在第一次投掷中赢了!你掷出了 " 
			+ firstDice + " 和 " + secondDice + " 总共为 " + throwSum);
			}
			else if (throwSum == 2 || throwSum == 3 || throwSum == 12) {
				System.out.println("抱歉,你点数不佳,你输了!你掷出了 " + firstDice +
				" 和 " + secondDice + " 总共为 " + throwSum);
			} else {
				playerPoint = throwSum;
				System.out.println("你掷出了 " + firstDice + " + " + secondDice + " 总共为 "
		        + playerPoint);
				System.out.println("你的点数是 " + playerPoint + " 现在,祝你好运。");
				
				while (throwSum != 7 ) {
					firstDice = 1 + (int) (Math.random() * 10) % 6;
					secondDice = 1 + (int) (Math.random() * 10) % 6;
					throwSum = firstDice + secondDice;
					
					if (throwSum != 7) {
						System.out.println("你掷出了 " + firstDice + " + " + secondDice + 
						" 总共为 " + throwSum);
						
						if (throwSum == playerPoint) {
							System.out.println("恭喜!你赢了。你达到了你的点数。");
						break;
						}
						System.out.println("你的点数是 " + playerPoint + "。祝你好运。");
					}
					 else {
						System.out.println("你掷出了 " + firstDice + " + " + secondDice + 
						" 总共为 " + throwSum);
						System.out.println("抱歉,你点数不佳,你输了。"); 
						System.out.println("在达到你的点数之前,你掷出了7。");
						break;
					}
				}		
			}
			System.out.println("你想再玩一次吗? yes/no: ");
            
                 // 即使用户输入 "no",循环也不会退出		
			proceed = input.nextLine();	
		}
		System.out.println("谢谢你的游玩。");
		enter.close();
		input.close();
	}
}
英文:

I want to create a game called Crap. The problem that I am facing is that the main while loop does not end despite the condition being set to false (by user inputing "no" when asked if they want to conitnue playing). What is the problem here? Comments are inserted where I think the problem is.

import java.util.Scanner;
public class crap {
public static void main(String[] args) {
System.out.println("You are about to play the game of Crap. Press Enter to continue.");
Scanner enter = new Scanner (System.in);
String hitEnter = enter.nextLine();
Scanner input = new Scanner(System.in);
String proceed = "yes";
// This loop does not exit even if proceed == "no"
while (proceed != "no"){
int playerPoint;
int firstDice = 1 + (int) (Math.random() * 10) % 6;
int secondDice = 1 + (int) (Math.random() * 10) % 6;
int throwSum = firstDice + secondDice;
if (throwSum == 7 || throwSum == 11) {
System.out.println("Congratulations! You win on your first roll! You rolled " 
+ firstDice + " and " + secondDice + " for a total of " + throwSum);
}
else if (throwSum == 2 || throwSum == 3 || throwSum == 12) {
System.out.println("Sorry, you crapped out, you lose! You rolled " + firstDice +
" and " + secondDice + " for a total of " + throwSum);
} else {
playerPoint = throwSum;
System.out.println("You rolled " + firstDice + " + " + secondDice + " which is "
+ playerPoint);
System.out.println("Your point is " + playerPoint + " now. Good luck.");
while (throwSum != 7 ) {
firstDice = 1 + (int) (Math.random() * 10) % 6;
secondDice = 1 + (int) (Math.random() * 10) % 6;
throwSum = firstDice + secondDice;
if (throwSum != 7) {
System.out.println("You rolled " + firstDice + " + " + secondDice + 
" which is " + throwSum);
if (throwSum == playerPoint) {
System.out.println("Congratulations! You win. You reached your point.");
break;
}
System.out.println("Your point is " + playerPoint + ". Good luck.");
}
else {
System.out.println("You rolled " + firstDice + " + " + secondDice + 
" which is " + throwSum);
System.out.println("Sorry, you crapped out, you lose."); 
System.out.println("You rolled 7 before reaching your point.");
break;
}
}		
}
System.out.println("Do you want to play again? yes/no: ");
// even if user enters "no" the loop does not exit		
proceed = input.nextLine();	
}
System.out.println("Thanks for playing.");
enter.close();
input.close();
}
}
</details>
# 答案1
**得分**: 1
你使用了错误的运算符。```!=```会检查左右两边的对象是否相同(例如,两个变量引用内存中的同一对象)。
你应该写成 ```while (!"no".equals(proceed))```。
我刻意没有写成 ```while (!proceed.equals("no"))```,因为如果字符串为空,你会得到一个空指针异常。
我不确定 ```Scanner.readLine()``` 是否会返回空字符串,所以在这里可能没有什么区别。但是按照我第一个示例中的“相反”方式编写通常更安全。
<details>
<summary>英文:</summary>
You are using the wrong operator. ```!=``` checks if the two objects on left and right side are the the same (e.g. two variables reference the same object in memory). 
You must write ```while (! &quot;no&quot;.equals(proceed) )```.
I did not write ```while (! proceed.equals(&quot;no&quot;) )``` on purpose because if the string is null then you would get a NullPointerException. 
I am not sure if Scanner.readLine() does ever return a null string, so it may make no difference here. But writing it in the &quot;reverse&quot; way as in my first example is more safely in general.
</details>
# 答案2
**得分**: 0
对于字符串(String),使用“==”运算符来比较给定字符串的引用,具体取决于它们是否引用相同的对象。当使用“==”运算符比较两个字符串时,如果字符串变量指向同一个Java对象,则返回true。否则,返回false。
您必须使用`.equals(String)`来比较字符串,如下所示:
```java
import java.util.Scanner;
public class crap {
public static void main(String[] args) {
System.out.println("You are about to play the game of Crap. Press Enter to continue.");
Scanner enter = new Scanner(System.in);
String hitEnter = enter.nextLine();
Scanner input = new Scanner(System.in);
String proceed = "yes";
// 即使proceed == "no",此循环也不会退出
while (!proceed.equals("no")) {
int playerPoint;
int firstDice = 1 + (int) (Math.random() * 10) % 6;
int secondDice = 1 + (int) (Math.random() * 10) % 6;
int throwSum = firstDice + secondDice;
if (throwSum == 7 || throwSum == 11) {
System.out.println("Congratulations! You win on your first roll! You rolled "
+ firstDice + " and " + secondDice + " for a total of " + throwSum);
} else if (throwSum == 2 || throwSum == 3 || throwSum == 12) {
System.out.println("Sorry, you crapped out, you lose! You rolled " + firstDice +
" and " + secondDice + " for a total of " + throwSum);
} else {
playerPoint = throwSum;
System.out.println("You rolled " + firstDice + " + " + secondDice + " which is "
+ playerPoint);
System.out.println("Your point is " + playerPoint + " now. Good luck.");
while (throwSum != 7) {
firstDice = 1 + (int) (Math.random() * 10) % 6;
secondDice = 1 + (int) (Math.random() * 10) % 6;
throwSum = firstDice + secondDice;
if (throwSum != 7) {
System.out.println("You rolled " + firstDice + " + " + secondDice +
" which is " + throwSum);
if (throwSum == playerPoint) {
System.out.println("Congratulations! You win. You reached your point.");
break;
}
System.out.println("Your point is " + playerPoint + ". Good luck.");
} else {
System.out.println("You rolled " + firstDice + " + " + secondDice +
" which is " + throwSum);
System.out.println("Sorry, you crapped out, you lose.");
System.out.println("You rolled 7 before reaching your point.");
break;
}
}
}
System.out.println("Do you want to play again? yes/no: ");
// 即使用户输入"no",循环也不会退出
proceed = input.nextLine();
}
System.out.println("Thanks for playing.");
enter.close();
input.close();
}
}
英文:

For a String, the == operator is used to comparing the reference of the given strings, depending on if they are referring to the same objects. When you compare two strings using == operator, it will return true if the string variables are pointing toward the same java object. Otherwise, it will return false .

You have to use .equals(String) to compare Strings, like so:

import java.util.Scanner;
public class crap {
public static void main(String[] args) {
System.out.println(&quot;You are about to play the game of Crap. Press Enter to continue.&quot;);
Scanner enter = new Scanner (System.in);
String hitEnter = enter.nextLine();
Scanner input = new Scanner(System.in);
String proceed = &quot;yes&quot;;
// This loop does not exit even if proceed == &quot;no&quot;
while (!proceed.equals(&quot;no&quot;)){
int playerPoint;
int firstDice = 1 + (int) (Math.random() * 10) % 6;
int secondDice = 1 + (int) (Math.random() * 10) % 6;
int throwSum = firstDice + secondDice;
if (throwSum == 7 || throwSum == 11) {
System.out.println(&quot;Congratulations! You win on your first roll! You rolled &quot; 
+ firstDice + &quot; and &quot; + secondDice + &quot; for a total of &quot; + throwSum);
}
else if (throwSum == 2 || throwSum == 3 || throwSum == 12) {
System.out.println(&quot;Sorry, you crapped out, you lose! You rolled &quot; + firstDice +
&quot; and &quot; + secondDice + &quot; for a total of &quot; + throwSum);
} else {
playerPoint = throwSum;
System.out.println(&quot;You rolled &quot; + firstDice + &quot; + &quot; + secondDice + &quot; which is &quot;
+ playerPoint);
System.out.println(&quot;Your point is &quot; + playerPoint + &quot; now. Good luck.&quot;);
while (throwSum != 7 ) {
firstDice = 1 + (int) (Math.random() * 10) % 6;
secondDice = 1 + (int) (Math.random() * 10) % 6;
throwSum = firstDice + secondDice;
if (throwSum != 7) {
System.out.println(&quot;You rolled &quot; + firstDice + &quot; + &quot; + secondDice + 
&quot; which is &quot; + throwSum);
if (throwSum == playerPoint) {
System.out.println(&quot;Congratulations! You win. You reached your point.&quot;);
break;
}
System.out.println(&quot;Your point is &quot; + playerPoint + &quot;. Good luck.&quot;);
}
else {
System.out.println(&quot;You rolled &quot; + firstDice + &quot; + &quot; + secondDice + 
&quot; which is &quot; + throwSum);
System.out.println(&quot;Sorry, you crapped out, you lose.&quot;); 
System.out.println(&quot;You rolled 7 before reaching your point.&quot;);
break;
}
}       
}
System.out.println(&quot;Do you want to play again? yes/no: &quot;);
// even if user enters &quot;no&quot; the loop does not exit     
proceed = input.nextLine(); 
}
System.out.println(&quot;Thanks for playing.&quot;);
enter.close();
input.close();
}
}

huangapple
  • 本文由 发表于 2020年9月28日 00:38:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/64090866.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定