`
夏莹_合肥
  • 浏览: 178411 次
  • 性别: Icon_minigender_1
  • 来自: 合肥
社区版块
存档分类
最新评论

有趣的剪刀石头布,外加老虎问题

 
阅读更多

java解决剪刀石头布,再加个老虎通杀的问题。

 

 

具体代码如下:

 

public class sdfd {

	public static String[] names = { "剪刀", "石头", "布", "老虎"};
	public static int[][] matrix = {
		{ -1, 0, 1, 0 },
		{ 1, -1, 0, 0},
		{ 0, 1, -1, 0},
		{ 1, 1, 1, -1}
	};
	
	public static void main(String[] args) {
		sdfd a = new sdfd();
		a.compare("剪刀", "石头");
		a.compare("剪刀", "布");
		a.compare("老虎", "石头");
	}
	
	public void compare(String name1, String name2) {
		
		int row = getSubIndex(name1, names);
		int col = getSubIndex(name2, names);
		
		int result = matrix[row][col];
		
		if(result == 1) System.out.println("赢");
		else if(result == 0) System.out.println("输");
		else if(result == -1) System.out.println("平");
	}
	
	public int getSubIndex(String name, String[] names) {
		
		for(int i = 0; i < names.length; i++) {
			if(names[i].equals(name)) {
				return i;
			}
		}
		
		return -1;
	}
}

 

数组names,和二维数组matrix可以从配置文件中读取。这种结构下,当新增比如说狮子时,原本的代码一行也不用修改,嘿嘿。

 

  • 大小: 29.4 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics