java 三个人猜数字 直到有人猜对为止

葫芦的运维日志

下一篇 搜索 上一篇

2014/02/11 15:33


public class GuessGame{
Player p1;
Player p2;
Player p3;
public void startGame(){
p1=new Player();
p2=new Player();
p3=new Player();

int guessp1=0;
int guessp2=0;
int guessp3=0;

boolean p1isRight= false;
boolean p2isRight=false;
boolean p3isRight=false;

int targetNumber=(int)(Math.random()*10);
System.out.println("I'm thinking of a number between 0 and 9...");
while(true){
System.out.println("Number to guess is"+ targetNumber);
p1.guess();
p2.guess();
p3.guess();
guessp1=p1.number;
System.out.println("Player one guessed"+guessp1);
guessp2=p2.number;
System.out.println("Player two guessed"+guessp2);
guessp3=p3.number;
System.out.println("Player three guessed"+guessp3);

if(guessp1==targetNumber){
p1isRight= true;
}
if(guessp2==targetNumber){
p2isRight=true;
}
if(guessp3==targetNumber){
p3isRight=true;
}
if(p1isRight || p2isRight || p3isRight){
System.out.println("We have a winner!");
System.out.println("Player one got it right?"+p1isRight);
System.out.println("Player two got it right?"+p2isRight);
System.out.println("Player three got it right?"+p3isRight);
System.out.println("Game is over!");
break;
}else
{
System.out.println("Players will have to try again");
}

}
}
}


public class Player{
     int number=0;
     public void guess(){
     number=(int)(Math.random()*10);
          System.out.println("I'm guessing "+ number);
     }

} 

public class GameLauncher
{
     public static void main(String[] args)
     {
          GuessGame game=new GuessGame();
          game.startGame();
     //     System.out.println("Hello World!");
     }
}
 /*c:\java>java GameLauncher
I'm thinking of a number between 0 and 9...
Number to guess is3
I'm guessing 1
I'm guessing 7
I'm guessing 0
Player one guessed1
Player two guessed7
Player three guessed0
Players will have to try again
Number to guess is3
I'm guessing 5
I'm guessing 6
I'm guessing 5
Player one guessed5
Player two guessed6
Player three guessed5
Players will have to try again
Number to guess is3
I'm guessing 3
I'm guessing 3
I'm guessing 0
Player one guessed3
Player two guessed3
Player three guessed0
We have a winner!
Player one got it right?true
Player two got it right?true
Player three got it right?false
Game is over!*/

 

葫芦的运维日志

上一篇 搜索 下一篇
© 冰糖葫芦甜(bthlt.com) 2019 王梓 赞助联系方式 陕ICP备17005322号