我知道如何创建数组,如下所示。但是我如何检查用户是否输入了相同的数字。我尝试使用if语句,但我不断收到错误。我也试过用一段时间。
我必须编写一个程序,在数组virtualenv
中生成并存储20个随机数,并要求用户输入他的猜测。如果它们的数字出现在数组中,则每次出现时得到2分,打印数组并找到幸运数字的所有位置。如果它没有出现在数组中,我必须打印数组的最低和最高值,并且只允许再尝试一次。如果玩家在第二次得到正确的情况下每次出场都得到1分。
virtualenvwrapper
答案 0 :(得分:0)
这样的东西应该可以正常工作,因为你希望看到数组中是否存在该值,它可以扩展为搜索并找到高/低值:
int counter = 0; //Assume not found at first
for (int i: Data) {
if (i==Integer.parseInt(input1)){
counter++;
}
}
System.out.println("The numer was found "+Integer.toString(counter)+" time(s).");
答案 1 :(得分:0)
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] data = new int[20];
int guess;
int times;
int score = 0;
int tries = 0;
fillArrayWithRandoms(data);
while (tries < 2) {
System.out.print("Guess a number: ");
guess = sc.nextInt();
if ((times = timesInArray(guess, data)) != 0) {
if (tries == 0)
score += 2 * times;
else
score += times;
printArray(data);
fillArrayWithRandoms(data);
System.out.println("You are lucky! Score: " + score + "\n");
} else {
tries++;
System.out.println("You are unlucky!");
if (tries < 2)
printBoundaries(data);
System.out.println();
}
}
System.out.println("Game Over! Your score: " + score);
}
private static void printArray(int[] data) {
for (int element : data) {
System.out.print(element + " ");
}
System.out.println();
}
private static void fillArrayWithRandoms(int[] data) {
for (int i = 0; i < data.length; i++) {
data[i] = (int) (Math.random() * 100);
}
}
private static int timesInArray(int guess, int[] data) {
int occurrence = 0;
for (int element : data) {
if (element == guess)
occurrence++;
}
return occurrence;
}
private static void printBoundaries(int[] data) {
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for (int element : data) {
if (element < min) {
min = element;
}
if (element > max) {
max = element;
}
}
System.out.println("Try a number between " + min + " and " + max);
}
}