简体   繁体   中英

Java - Checking if a variable is equal to any of the array elements

I am making a trivia game, in this one section I am trying to check if the variable 'a' is equal to any of the elements in the array. In this particular context, I'm trying to see if it is equal to 3 OR 1964. NOTE: I shortened the code to get rid of any extra code, and the '//...' represents that I skipped several lines of code.

class Main {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);
//...
int[] answer1 = {3, 1964}
//...
do {
  System.out.println("Enter your answer now.");
  int a = input.nextInt();
    if (a != answer1[]) {
      System.out.println("Incorrect. Try again.");
      guess_count++;
    } else {
      System.out.println("Correct! You gained 1 point!");
      pointTotal++;
      guessCount++;
    }

Since you're working with an array of primitives, maybe you want to work with IntStream (however, there are many ways and it depends on what benefits you are looking for.):

    int[] array = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    final int expectedInt = 10;
    boolean isExpectedIntPresent = Arrays.stream(array).filter(
            (element) -> element == expectedInt).findFirst().isPresent();

You could use contains from the List interface eg

if(Arrays.aslist(answer1).contains(a)){
  // do stuff
}

You could also changer your array to a list, then you would not need to use Arrays.asList

There are already a couple of answers proposing some code so I will answer from a more "didactic" point of view.

If you want to work exclusively with arrays there is more than one way to do so.

  • If the array is not sorted, the most intuitive approach is Linear Search . Basically you iterate through the array, compare each element to your variable and stop/return when you find it. Pretty straightforward and easy to implement.
  • If the array is sorted, Binary Search is, in general, what you should go for. This approach takes advantage of the fact that the array is sorted and basically discards half of the array at each iteration. I leave it to you to look into the specifics.

Alternatively you could also exploit interfaces such as Lists or Streams , as others correctly suggested.

Anyhow, even with a quick Google search you can find plenty of examples of such a problem (just look for Searching algorithms and you're set to go).

You can use a HashMap to store the elements (against which you want to check your guesses) as keys and use the method.containsKey() to check if the HashMap contains the element or not. Also, don't forget to import HashMap.

Scanner input = new Scanner(System.in);
//...
int[] answer1 = {3, 1964};
HashMap<Integer, Integer> map = new HashMap<>();
for(int i = 0; i < answer1.length; i++){
    map.put(answer1[i], 1);
}
//...
do {
  System.out.println("Enter your answer now.");
  int a = input.nextInt();
    if (!map.containsKey(a)) {
      System.out.println("Incorrect. Try again.");
      guess_count++;
    } else {
      System.out.println("Correct! You gained 1 point!");
      pointTotal++;
      guessCount++;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM