Reputation: 1
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++;
}
Upvotes: 0
Views: 2007
Reputation: 455
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++;
}
Upvotes: 0
Reputation: 434
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();
Upvotes: 1
Reputation: 53
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.
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).
Upvotes: 0
Reputation: 37594
You could use contains
from the List
interface e.g.
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
Upvotes: 0