blogspot.com-GA4

星期二, 8月 22, 2006

用簡單的類別物件做剪刀、石頭、布

/**
* createdate 2006/08/15
* @author ken
*/
public class Finger {
// 指定名稱
private String name;
// 選擇值
private String value;
// 獲勝次數
private int iwin;

// 無參數建構子
public Finger(){}

// 有參數建構子
public Finger(String name){
this.name = "";
value = "";
iwin = 0;
this.name = name;
}

/**
* 類別方法,隨機取得電腦出拳
* @return
*/
public static String getRandom(){
int icomp = (int)(Math.random()*10%3 + 1);
return String.valueOf(icomp);
}

public int getIwin() {
return iwin;
}
public void setIwin(int iwin) {
this.iwin = iwin;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}

import java.util.Scanner;

public class FingerValue {
public static void main(String[] args){
Finger fguser = new Finger();
String[] sa_finger = {"剪刀","石頭","布"};

fguser.setName("User");

Scanner scr = new Scanner(System.in);
System.out.println("select one you wait:");
System.out.println("1.剪刀");
System.out.println("2.石頭");
System.out.println("3.布");

Finger fgcomp = new Finger("computer");

while (fguser.getIwin() < 5 && fgcomp.getIwin() < 5){
fgcomp.setValue(Finger.getRandom());
fguser.setValue(scr.next());

if (fguser.getValue().equals(fgcomp.getValue())){
System.out.println("same");
}else if ((fguser.getValue().equals("1")&&fgcomp.getValue().equals("3")) ||
(fguser.getValue().equals("2")&&fgcomp.getValue().equals("1")) ||
(fguser.getValue().equals("3")&&fgcomp.getValue().equals("2"))){
System.out.println("You win!!");
fguser.setIwin(fguser.getIwin()+1);
}else{
System.out.println("You false!!");
fgcomp.setIwin(fgcomp.getIwin()+1);
}

System.out.println(fguser.getName() +":出" + sa_finger[Integer.parseInt(fguser.getValue())-1]);
System.out.println(fgcomp.getName() +":出" + sa_finger[Integer.parseInt(fgcomp.getValue())-1]);
}

System.out.println(fguser.getName() +":" + fguser.getIwin());
System.out.println(fgcomp.getName() +":" + fgcomp.getIwin());
}
}

沒有留言: