本帖最后由 唐晓 于 2013-1-19 09:01 编辑
/*电脑随机出的石头剪子布*/
public class Computer {
private String fist;
public String getFist() {
return fist;
}
public void setFist(String fist) {
this.fist = fist;
}
//1 2 3 剪刀 石头 布
public int ShowFist()
{
int result = -1;
Random r=new Random();
result= (int)(Math.random()*2+1);
switch (result)
{
case 1:
fist = "剪刀";
break;
case 2:
fist = "石头";
break;
case 3:
fist = "布";
break;
}
return result;
}
}
/*你自己的出拳*/
public class Player {
private String fist;
public String getFist() {
return fist;
}
public void setFist(String fist) {
this.fist = fist;
}
public int ShowFist(String fist)
{
this.fist = fist;
int result = -1;
if (fist == "剪刀")
{
result = 1;
}
else if(fist == "石头")
{
result = 2;
}
else if(fist == "布")
{
result = 3;
}
return result;
}
}
/*判断输赢*/
public class Choose {
public String Check(int player, int pc)
{
String result = "";
int tmp = player - pc;
if (tmp == 0)
{
result = "平手";
}
else if (tmp == 1 || tmp == -2)
{
result = "YOU WIN!";
}
else
{
result = "YOU LOST!";
}
return result;
}
}
主程序运行:异常没处理,这里全部都抛出去了。
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
System.out.println("请输入石头剪子或者布:");
//创建输入流
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = null;
//读取一行数据
line=br.readLine();
Check(line);
}
private static void Check(String fist)
{
Player player = new Player();
player.ShowFist(fist);
Computer pc = new Computer();
pc.ShowFist();
Choose j = new Choose();
//判断输赢
System.out.println("你出的是:"+player.getFist()+"----电脑出的是:"+pc.getFist()+"-----"+j.Check(player.ShowFist(fist), pc.ShowFist()));
} |