Java 为什么赢了';当条件满足时,该方法是否返回true?
我正在使用GUI用Netbeans编写一个游戏。在游戏中,随机生成15-30块石头,用户和计算机轮流移除1-3块石头,直到没有剩下为止。拿最后一块石头的最后一个玩家输了。我的问题是我的方法(validIn())不会在playerMove()中使用,因此即使满足条件,游戏也不会更新。 我认为问题在于:Java 为什么赢了';当条件满足时,该方法是否返回true?,java,methods,netbeans,boolean,user-input,Java,Methods,Netbeans,Boolean,User Input,我正在使用GUI用Netbeans编写一个游戏。在游戏中,随机生成15-30块石头,用户和计算机轮流移除1-3块石头,直到没有剩下为止。拿最后一块石头的最后一个玩家输了。我的问题是我的方法(validIn())不会在playerMove()中使用,因此即使满足条件,游戏也不会更新。 我认为问题在于: private boolean validIn(int num){ // return num < 3 || num > 1 || num < totalStone
private boolean validIn(int num){
//
return num < 3 || num > 1 || num < totalStone;
}
public void playerMove(){
// Geting the user input
int userIn = Integer.parseInt(txtIn.getText());
// Declaring and assigning a boolean
boolean check = false;
// If the boolean returns true
if (check == true) {
// Subtracting how much the player took from the total amount of rocks
totalStone -= userIn;
// Displaying how many rocks were taken and how many are left
txtOut.setText(txtOut.getText() +"\nYou picked up " +userIn +" stone(s). There are " +totalStone +" stone(s) left.");
}
// Else,
else {
// Assign the boolean check to what the method validIn returns
check = validIn(userIn);
}
}
public void checkWinner(String player){
// If there are no more stones left,
if (totalStone == 0){
// Display a message that says who won
txtOut.setText(txtOut.getText() +"\nThere are no more stones left. "+player +" wins!");
}
}
private void btnEnterActionPerformed(java.awt.event.ActionEvent evt) {
//
if (totalStone > 0){
// Display how many rocks there are
txtOut.setText(txtOut.getText() +"\nThere are " +totalStone +" stone(s).");
// The player does their move
playerMove();
// Checking if the computer won
checkWinner("The computer");
// Computer does a turn
computerMove();
// Checking if the player won
checkWinner("The player");
}
//
else if (totalStone == 0){
//
txtOut.setText(txtOut.getText() + "\nThe game has ended.");
}
}
private boolean validIn(int num){
//
返回num<3 | | num>1 | | num0){
//显示有多少块石头
setText(txtOut.getText()+“\n有“+totalStone+”个石头”);
//球员移动
playerMove();
//检查电脑是否赢了
支票赢家(“计算机”);
//计算机起作用
computerMove();
//检查玩家是否赢了
支票赢家(“玩家”);
}
//
否则如果(totalStone==0){
//
txtOut.setText(txtOut.getText()+“\n游戏已经结束。”);
}
}
在您的代码中,我看到布尔方法总是返回true,因为您使用
|| (OR)
任何小于3的数字都将返回true,大于1的数字也将返回true
在您的IF条件下,我没有看到您将变量check
设置为true,但您仍然有条件check
为true
,因此我想知道如何使用此变量检查您的条件?
那么它如何跳入if语句呢?对于您的validIn方法,您需要考虑一下您的方法返回语句的条件 它是这样写的:
- 如果num是任何小于3的值,如0、-50、1、2则返回true,如果不是,则返回
- 如果num是任何大于1的值(如2、3、1020、323243),则返回true;如果不是,则返回
- 如果num小于totalStones则返回true,如果不小于,则返回false
return num < 3 && num > 1 && num < totalStone;
returnnum<3&&num>1&&num
- 仅当num小于3且num大于1且num小于时,才返回true李>
return num <= 3 && num >= 1 && num < totalStone;
returnnum=1&&num
这样,如果num包含1、2或3,且其中任何一个值小于totalStones,则返回true,否则返回false
intcomin=(int)(Math.random()*2)+1
//声明和分配布尔值
布尔检查=假;
//如果生成的数量大于总石头数,
如果(check==true&&validIn(userIn)==true){…}
private boolean validIn(int num){
返回num<3 | | num>1 | | num