나는 다음과 같은 3 종류가 있습니다자바 문 평가
package GameboardPack;
public class Gameboard {
public static void main(String[] args) {
boolean iswin =true;
Game g = new Game();
Player p1= new Player();
Player p2 = new Player();
Player p3 = new Player();
Player p4 = new Player();
int counter=0;
while(iswin){
p1.getNum();
p2.getNum();
p3.getNum();
p4.getNum();
g.getNum();
iswin=!(g.num==p1.num);
p1.won=!iswin;
iswin=!(g.num==p2.num);
p2.won=!iswin;
iswin=!(g.num==p3.num);
p3.won=!iswin;
iswin=!(g.num==p4.num);
p4.won=!iswin;
counter++;
}
System.out.println("the winner is"+" p1 "+p1.won+" p2 "+p2.won+" p3 "+p3.won+" p4 "+p4.won+" counter "+counter);
System.out.println(" GAME NUM "+g.num+" p1 NUM "+p1.num+" p2 NUM "+p2.num+" p3 NUM "+p3.num+" p4 NUM "+p4.num+" counter "+counter);
}
}
2 등석 :
package GameboardPack;
public class Player {
public int num;
boolean won=false;
private void guess(){
num=(int) (Math.random()*100);
}
public int getNum() {
guess();
return num;
}
public Player() {
super();
// TODO Auto-generated constructor stub
}
public Player(int num, boolean won) {
super();
this.num = num;
this.won=won;
}
}
세 번째 클래스 : 아무리 내가 실행 횟수 어떤 이유
package GameboardPack;
public class Game extends Player {
public Game(int num, boolean won) {
super(num, won);
// TODO Auto-generated constructor stub
}
public Game() {
super();
// TODO Auto-generated constructor stub
}
}
이 코드는 누가 이길 것이며, 항상 "p4"라고하는 네 번째 것, 승리 :
The winner is p1 false p2 false p3 false p4 true counter 44
GAME NUM 70 p1 NUM 4 p2 NUM 77 p3 NUM 47 p4 NUM 70 counter 44
이유를 설명해주세요.
"p4"는 항상 승리 할 것입니다. 게임 루프가 끝날 때까지 멈추지 않을 것이기 때문입니다. – Tom
게임의 번호 중 하나가 게임의 번호와 일치하면 게임을 중지하고 "iswin"을 false로 설정하고 루프를 종료하십시오. 나는 왜 p4가 우승하는지 알지 못한다. – Z3d4s
코드를 디버그하면 문제가 표시됩니다. 플레이어가이기는지를 확인할 때마다 iswin 값을 변경합니다. p2를 얻었지만 코드 순서에 따라 iswin 값을 변경하는 p3 검사가 나온다고 해봅시다. 그 후 p4 검사가 오면 iswin 값이 다시 변경됩니다. iswin 값을 변경하는 p4 이후의 다른 검사가 없으므로 p4만이 승리합니다. – durban