package lotto;
import java.util.Random;
import java.util.Scanner;
public class lotto {
public static void main(String [] args){
Scanner scan = new Scanner(System.in);
int restarto = 0;
double[] inputs = new double[6];
do{
////////////////////////ask for input
System.out.println("Welcome to the lotto program. Please enter " +inputs.length + " values:");
for(int i = 0; i < inputs.length; i++)
inputs[i] = scan.nextDouble();
///////////////////////create random numbers
double [] elArry = new double[6];
Random random = new Random();
for(int i = 0; i < elArry.length; i++){
elArry[i] = random.nextInt(101);
}
//////////////////////check for similarities
如何比较用户输入的数字和我随机生成的数字,看看用户是否正确猜到了这些数字?
//////////////////////print results
//////////////////////restart?
System.out.println("Would you like to guess again on the same lotto numbers?");
System.out.println("1.Yes");
System.out.println("2.No");
restarto=scan.nextInt();
}while(restarto == 1);
}
}
答案 0 :(得分:1)
如果有必要,只知道所有人都被猜对了:
boolean same = true;
for(int i = 0; i < elArry.length; i++) {
if (elArry[i] != inputs[i]) {
same = false;
break;
}
System.out.println(same? "You have guessed correctly!" : "You guessed wrong!");
如果您对此方法做得很好,例如robotlos建议,则代码会更漂亮:
private static boolean guessedRight() {
for (int i = 0; i < elArry.length; i++)
if (elArry[i] != inputs[i]) return false;
return true;
}
...
System.out.println(guessedRight()? "You have guessed correctly!" : "You guessed wrong!");
但说实话,您可以在用户输入后直接生成随机数,这将使您的代码更紧凑:
boolean same = true;
for(int i = 0; i < inputs.length; i++) {
inputs[i] = scan.nextInt();
if(inputs[i] != random.nextInt()) same = false;
//there is no reason to generate double if the user guesses with ints
}
//if same is false, at least one number was not guessed right
答案 1 :(得分:0)
对两个数组进行排序,然后检查它们是否相等。如果他们这样做,那么他们是一样的:
Arrays.sort(inputs);
Arrays.sort(elArry);
return (Arrays.equals(inputs, elArry));
答案 2 :(得分:0)
将布尔数组设为6,然后进行比较输入和rndNum的循环。
boolean[] correct = new boolean[6];
for (int i = 0; i < 6; i++) {
if (inputs[i]==elArry[i]) {
correct[i] = true;
}
有很多方法可以解决这个问题,我猜这是其中之一。
答案 3 :(得分:0)
由于两个数组必须具有相同顺序的相同值,因此yoy可以检查它们在技术上是否相等
班级Arrays有等于你的方法......
if (Arrays.equals(inputs, elArry)) {
System.out.println("You won... :)");
} else {
System.out.println("You were not even close... :(");
}
答案 4 :(得分:0)
您可以编写一个循环来检查输入数组的第i个条目是否也包含在elArray中,前提是您对猜测顺序不感兴趣:
int counter = 0;
for(int i = 0; i < inputs.length; i++) {
if (IntStream.of(elArray).anyMatch(x -> x == inputs[i])) {
counter += 1;
}
}
现在,计数器变量包含正确猜测数字的数量。您也可以修改它以跟踪哪些数字是正确的。