这个小程序是模仿现实生活中的猜拳所写的,通过随机数实现电脑的出拳,里面有3个类,分别为Person类,Computer类及Game类。其中Person类和Computer类分别记录用户和电脑的用户名、输赢次数以及所出的拳。Game类来对比用户和电脑所出的拳,输出相应的语句。以下为代码: (1)Person类 package com.GuessFist; import java.util.Scanner; public class Person { public String Name; public int Score; public void GetName(String name){ Name=name; } public int GetFist(){ Scanner input=new Scanner(System.in); int Fist=input.nextInt(); if (Fist<1&&Fist>3) { System.out.println("Warning!输入错误"); return 0; } switch (Fist) { case 1: System.out.println("\t玩家"+Name+",您出了剪刀"); return Fist; case 2: System.out.println("\t玩家"+Name+",您出了石头"); return Fist; case 3: System.out.println("\t玩家"+Name+",您出了布"); return Fist; default: System.out.println("Warning!输入错误,请重新输入"); GetFist(); break; } return 0; } } (2)Computer类 package com.GuessFist; import java.util.Random; public class Computer { public String Name; public int Score; public void GetName(String name){ Name=name; } public int GetFist(){ Random r=new Random(); int Fist=r.nextInt(2)+1; switch (Fist) { case 1: System.out.println("\t电脑"+Name+"出了剪刀"); return Fist; case 2: System.out.println("\t电脑"+Name+"出了石头"); return Fist; case 3: System.out.println("\t电脑"+Name+"出了布"); return Fist; default: break; } return 0; } } (3)
时间: 2024-11-19 03:48:44