package a1;
import java.util.Scanner;
public class Caiquan {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int c = 1;
while (c == 1){
System.out.println("玩家请出拳");
//玩家出拳
int b = sc.nextInt();
String bHand = getHand(b);
// 2 电脑开始出拳(生成一个随机数)
int a = (int)(Math.random()*3);
String aHand = getHand(a);
if((a == 0 && b == 2) || (a == 1 && b == 0) || (a ==2 && b ==1)) {
System.out.println("电脑出拳-" + aHand + ";玩家出拳-" + bHand + ";电脑胜利");
}else if((a == 0 && b == 0) || (a == 1 && b == 1) || (a ==2 && b ==2)) {
System.out.println("电脑出拳-" + aHand + ";玩家出拳-" + bHand + ";平局");
} else {
System.out.println("电脑出拳-" + aHand + ";玩家出拳-" + bHand + ";玩家胜利");
}
System.out.println("是否继续?y-继续 n-退出");
String tar = sc.next();
if("n".equals(tar)) {//equals()判断两个字符串的值是否相等
c = 2;
}
}
System.out.println("游戏结束!!!");
}
public static String getHand(int h) {
if(h == 0)return"剪刀";
if(h == 1)return"石头";
if(h == 2)return"布";
return"";
}
}
运行结果:
关于键盘输入:
//创建一个scanner类,开启键盘输入
Scanner sc = new Scanner(System.in);
//获取从键盘输入的值,并且将其转换为整数类型
int no = sc.nextInt();
既然说到这了,那我就演示一下这个Scanner
package abs;
import java.util.Scanner;
public class LX {
public static void main(String[] arg) {
System.out.println("输入一个数字");
Scanner shuzi = new Scanner(System.in);
int a = shuzi.nextInt();
System.out.println("输入一个文字");
// Scanner wenzhi = new Scanner(System.in);
String b = shuzi.next();
System.out.println("您输入的数字为:"+a);
System.out.println("您输入的文字为:"+b);
}
}
运行结果(直接在控制台输入就好):