/**
有個人 小范 設計他的成員變數. 成員方法, 可以電腦猜拳. 電腦每次都會隨機生成 0, 1, 2
0 表示 石頭 1 表示剪刀 2 表示 布
并要可以顯示 小范 的輸贏次數(清單), 假定 玩三次.
思路: 實作一次猜拳 → 實作無限回圈次猜拳(輸入3退出) → 使用陣列保存每次猜拳結果
1.使用亂數生成系統的出拳,控制臺輸入Tom的出拳
2.比較引數 0 > 1 , 1 > 2 , 2 > 0 .輸出結果
3.使用do...while 回圈 實作無限次猜拳
4. 使用二維陣列 arr[n][3] 保存猜拳結果 , n為猜拳次數,arr[n][0] 為系統出拳
arr[n][1] 為 Tom 出拳 ,arr[n][2] 為 猜拳結果 ,動態更新arr,
5. 最后顯示出一共贏了多少次,輸了多少次,平局多少次
*/
import java.util.Scanner;
public class HomeWork {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("請輸入你的名字:");
String name = input.next();
Person p = new Person(name);
p.mora(name);
}
}
class Person
{
String name;
int out; //出拳引數
Scanner input = new Scanner(System.in);
public Person(){}
public Person(String name){
this.name = name;
}
public void mora(String name){ //猜拳方法,name用于最后列印輸出 輸贏結果
int count = 0; // 用來標志 第幾次猜拳
int[][] arr = new int[1][3]; //使用二維陣列 arr[n][3] 保存猜拳結果
do{
int systemIn = (int)(Math.random()*2 + 1); //生成 0-2的亂數
// System.out.println(systemIn);
int res = 0; // 保存猜拳結果,-1為輸 0為平局 1為贏
System.out.println("請出拳(0 表示石頭,1 表示剪刀,2 表示布 ,3退出):");
out = input.nextInt();
//保護機制
while(out<0 || out>4){
System.out.println("輸入錯誤!請重新輸入(0 表示石頭,1 表示剪刀,2 表示布,3退出):");
out = input.nextInt();
}
if(out == 3){ //退出
break;
}
switch(systemIn){ //判斷輸贏
case 0: //電腦出石頭
if(out == 0){
res = 0;
}else if(out == 1){
res = -1;
}else{
res = 1;
}
break;
case 1: //電腦出剪刀
if(out == 0){
res = 1;
}else if(out == 1){
res = 0;
}else{
res = -1;
}
break;
case 2: //電腦出布
if(out == 0){
res = -1;
}else if(out == 1){
res = 1;
}else{
res = 0;
}
break;
}
switch(res){ //輸出結果
case -1:
System.out.println("你輸了!");
break;
case 0:
System.out.println("平局!");
break;
case 1:
System.out.println("你贏了!");
break;
}
//保存結果
arr[count][0] = systemIn; //arr[n][0] 為系統出拳
arr[count][1] = out; //arr[n][1] 為 Tom 出拳
arr[count][2] = res; //arr[n][2] 為 猜拳結果
count++; //改變count的值,準備進行下一次猜拳
//因為count是從0開始的,這里要先進行count++,再陣列擴容,不然會出現陣列下標越界例外,
int[][] temp = new int[count+1][3]; //建立中間陣列,進行陣列擴容
for(int i =0;i<arr.length;i++){
for(int j = 0;j<arr[i].length;j++){
temp[i][j] = arr[i][j];
}
}
arr = temp;
}while(out != 3);
//退出回圈后,輸出列印進行過的對局結果,
//列印結果的同時,累加變數 winCount ,loseCount ,drawCount
int winCount = 0; //贏的次數
int loseCount = 0; //輸的次數
int drawCount = 0; //平局次數
for(int k = 0;k <count;k++){
switch(arr[k][2]){ //根據輸贏進行判斷
case -1:
System.out.printf("第%d次猜拳 系統出拳 %S ,你出拳 %S ,你輸了!",(k+1),print(arr[k][0]),print(arr[k][1]));
loseCount++;
break;
case 0:
System.out.printf("第%d次猜拳 系統出拳 %S ,你出拳 %S ,平局!",(k+1),print(arr[k][0]),print(arr[k][1]));
drawCount++;
break;
case 1:
System.out.printf("第%d次猜拳 系統出拳 %S ,你出拳 %S ,你贏了!",(k+1),print(arr[k][0]),print(arr[k][1]));
winCount++;
break;
}
System.out.println();
}
System.out.printf("%S一共贏了%d次,輸了%d次,平局%d次,\n",name,winCount,loseCount,drawCount);
}
public String print(int a){ //用于輸出石頭 剪刀 布
String out = "";
if(a == 0){
out = "石頭";
}else if(a == 1){
out = "剪刀";
}else{
out = "布";
}
return out;
}
}

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/227799.html
標籤:Java
