猜拳游戏(类和对象)
package Demo02;
import java.util.Scanner;
public class User
{
String name;
int score;
public int showFist()
{
System.out.println("请出拳:1.剪刀\t2.石头\t3.布");
Scanner input=new Scanner(System.in);
int choice=input.nextInt();
if (choice==1)
{
System.out.println("你出了剪刀");
}else if (choice==2)
{
System.out.println("你出了石头");
}else if (choice==3)
{
System.out.println("你出了布");
} else {
System.out.println("输入有误");
}
return choice;
}
}
package Demo02;
public class Computer
{
String name;
int score;
public int showFist()
{
//随机数
int choice=(int)(Math.random()*3)+1;
if (choice==1)
{
System.out.println(name+"你出了剪刀");
}else if (choice==2)
{
System.out.println(name+"你出了石头");
}else if (choice==3)
{
System.out.println(name+"你出了布");
} else {
System.out.println(name+"输入有误");
}
return choice;
}
}
package Demo02;
import java.util.Scanner;
public class Game
{
//对象里面可以套对象 (嵌套)
User user; //User 默认值为 null 需要user=new User();
Computer computer;
int cout;//对战次数
//初始化:设置自己的名字 对手的名字,积分0
//NullPointerException: null.属性 null.方法()
public void init()
{
user =new User();
Scanner input=new Scanner(System.in);
System.out.println("请输入你的姓名");
String name=input.next();
user.name=name; //将键盘敲的属性变成user的属性
user.score=0;
System.out.println("请选择你的对手:\n1.张三\t2.李四\t3.王五");
int choice=input.nextInt();
computer=new Computer();
computer.score=0;
//转换
switch (choice)
{
case 1:
computer.name="张三";
break;
case 2:
computer.name="李四";
break;
case 3:
computer.name="王五";
break;
default:
System.out.println("输入有误!");
}
System.out.println("你选择了与TA对战:"+computer.name);
}
//开始游戏
public void start() {
Scanner input = new Scanner(System.in);
init();
String isContinue =null;
do {
int userFist = user.showFist();
int computerFist = computer.showFist();
calcResult(userFist, computerFist);
System.out.println("是否继续?y/ 其他(结束)");
isContinue = input.nextLine();
} while ("y".equals(isContinue));
showResult(user,computer);
}
//计算每一轮的结果
public void calcResult(int userFist,int computerFist)
{
if ((userFist==1&&computerFist==3)||(userFist==2&&computerFist