📄 randomnumθ
字号:
package com.tarena.day03;
import java.util.Arrays;
import java.util.Scanner;
public class RandomNum {
int[] nums = new int[4]; //保存随机生成数
int[] temp = new int[4]; //保存输入的数
public void setNum(){ //生成随机不相同的四个0~9之间的数
out:for(int i=0; i<nums.length; i++){
int temp = (int)(Math.random()*10);
nums[i] = temp;
for (int j = 0; j < i; j++) {
if(temp==nums[j]){
--i;
continue out;
}
}
}
}
public void setTemp(int temp, int i){ //输入数字
this.temp[i] = temp;
}
public boolean guessSuccess(){ //判断是否猜数成功
return Arrays.equals(nums, temp);
}
public void compareNum(){ //判断猜正确的数字位置是否相同
int a=0;
int b=0;
for (int i = 0; i < temp.length; i++) {
for (int j = 0; j < nums.length; j++) {
if(temp[i]==nums[i] && i==j){
++a;
}else if(temp[i]==nums[j] && i!=j){
++b;
}
}
}
System.out.println("-----" + a + "a" + b + "b");
}
public void print(){
for (int j = 0; j < temp.length; j++) { //显示输入的数
System.out.print(temp[j]+" ");
}
}
public void printRandom(){
for (int i = 0; i < nums.length; i++) { //显示机器随机的数
System.out.print(nums[i]+" ");
}
System.out.println();
}
}
class Test{
public static void main(String[] args) {
RandomNum rn= new RandomNum();
rn.setNum();
int chances = 7;
System.out.println("Guess Number Game Start! You have " + chances + " chances");
for (int i = 0; i < chances; i++) { //只允许猜7次
int[] temp = new int[4];
re:for (int j = 0; j < temp.length; j++) { //分别输入4个数字
System.out.println("Please enter the " + (j+1) + "th number:");
Scanner sc = new Scanner(System.in);
temp[j] = sc.nextInt();
if(temp[j]<0 || temp[j]>9){ //判断输入是否有效
System.out.println("error input! Please re-enter the " + (j+1) + "th number:");
--j;
continue re;
}
}
for (int n=0; n<temp.length; n++) { //分别传递4个数
rn.setTemp(temp[n], n);
}
rn.print(); //打印出输入的数字
rn.compareNum(); //打印出比较结果
if(rn.guessSuccess()){ //判断如果成功则退出
System.out.println("Congratulation!! You get it!");
break;
}else{
if(i!=(chances-1)){
System.out.println("You have " + (chances-1-i) + " chances!");
}else{
System.out.println("Sorry! You have no chance!");
System.out.print("The Random number is ");
rn.printRandom();
}
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -