gpt4 book ai didi

java - Java 中的 equals 方法不起作用

转载 作者:行者123 更新时间:2023-12-01 07:04:45 25 4
gpt4 key购买 nike

所以我在下面的类中有我的 equals 方法,当 if 语句为 true 时,我似乎没有返回 true!我似乎无法找出原因...

public class Player {

private int[] anyplayer = new int[5];

// constructor for each player at the table

public Player(int[] anyplayer) {

this.anyplayer = anyplayer;
}

// checks if the player has a winning bet in the european roulette

public boolean europeanequals(){
boolean truth = false;
for (int i = 0; i < anyplayer.length; i++) {
if (roulettedriver.eurowinningnumber == anyplayer[i]) {
truth = true;}
else {
truth = false;
}
}
return truth;
}

这是我调用该方法的驱动程序:

public class roulettedriver {

// declaring the two roulettes
final static int[] europeanroulettegame = {0,32,15,19,4,21,2,25,17,34,6,27,13,36,11,30,8,23,10,5,24,16,33,1,20,14,31,9,22,18,29,7,28,12,35,3,26};
final static int[] americanroulettegame = {0,28,9,26,30,11,7,20,32,17,5,22,34,15,3,24,36,13,1,00,27,10,25,29,12,8,19,31,18,6,21,33,16,4,23,35,14,2};

// declaring the two winning numbers
public static int eurowinningnumber = europeanroulette.getRandom(europeanroulettegame);
public static int uswinningnumber = americanroulette.getRandom(americanroulettegame);


public static void main(String[] args) {


Scanner keyin = new Scanner(System.in);

// initializing the six players (First player)
int[] player1 = {-1,-1,-1,-1,-1}; // the numbers are set to -1 because 0 is a winning number
Player first_player = new vipplayer(player1); // First player is automatically a VIP
try{

for(int i=0;i<=5;i++) {

player1[i] = Integer.parseInt(keyin.nextLine());

}
}

catch(NumberFormatException e){

System.out.println("Player 2 : ");
}

// booleans are set to true if the bets match the randomly generated number

boolean winbet1 = first_player.europeanequals();

基本上我的平等并没有比较我认为的正确值...似乎无法使这项工作成功?有什么意见吗?该值应该以 boolean 值 winbet1

形式返回

最佳答案

即使找到匹配项,您的代码也会继续运行,可能会将 truth 重置回 false,然后返回。

您需要像这样更改方法:

public boolean europeanequals(){
for (int i = 0; i < anyplayer.length; i++) {
if (roulettedriver.eurowinningnumber == anyplayer[i]) {
return true;
}
}
return false;
}

或使用 for-each 循环:

public boolean europeanequals(){
for (int number : anyplayer) {
if (roulettedriver.eurowinningnumber == number) {
return true;
}
}
return false;
}

关于java - Java 中的 equals 方法不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28487194/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com