大一刚学c的时候以前写过c语言版的。
- Math:针对数学进行运算的类
- 特点:没有构造方法,因为它的成员都是静态的
- 产生随机数:
public static double random(): 产生随机数,范围[0.0,1.0) - 产生1-100之间的随机数
int number = (int)(Math.random()*100)+1; - 猜数字小游戏案例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| class MathDemo { public static void main(String[] args) {
for(int x=0; x<100; x++) { int number = (int)(Math.random()*100)+1; System.out.println(number); } } }
|
小游戏
该游戏可以由程序随机产生或由用户输入四个0到9之间的数字,且不重复。玩游戏者通过游戏提示输入八次来匹配上面所输入的数字。A表示位置正确且数字正确,B表示数字正确而位置不正确。
算法: 可以直接算出A类的数目,但是B类的数目直接算出或许会很麻烦,正好我们可以先算出C类数目恰好减去A类就是B类了。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
| package caishuzi;
import java.util.Scanner;
class Num { private int[] a= {0,0,0,0}; public Num() {} public void setx() {
a[0]=(int)Math.random()*10+1; for(int i=1;i<4;i++) { int t=(int)(Math.random()*10); for(int j=0;j<i;j++) { if(t==a[j]) { t=(int)(Math.random()*10); j=0; } } a[i]=t; } } public int[] getx() { return a; } public void show() { System.out.println(); for(int i=0;i<4;i++) System.out.print(a[i]+" "); System.out.println(); } }
public class caishuzi { public static void main(String agrs[]) { int a[] = {0,0,0,0},b[] = {0,0,0,0}; System.out.println("* * * *\n请输入4个数字!A表示位置数字都正确,B表示数字正确位置错误。"); Scanner sc=new Scanner(System.in); Num n=new Num(); n.setx(); a=n.getx();
for(int k=0;k<10;k++) { int A=0,B=0,C=0; for(int i=0;i<4;i++) { b[i]=sc.nextInt(); } sc.close(); for(int i=0;i<4;i++){ if (b[i]==a[i])A++; for(int j=0;j<4;j++){ C=b[i]==a[j]?++C:C; if (b[i]==a[j])break; } } B=C-A; if(A==4) { System.out.println("恭喜猜对啦!"); }else { System.out.println(A+"A"+B+"B"); } } }
}
|
一次游戏过程
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| * * * * 请输入4个数字!A表示位置数字都正确,B表示数字正确位置错误。 0 1 2 3 0A1B 0 1 2 4 0A1B 0 1 2 5 1A1B 6 1 2 5 1A2B 1 6 2 5 3A0B 1 6 7 5 恭喜猜对啦!
|