2

Hey guys I am taking a high school course for computer science and we just started our second unit arrays and I am not sure how to do a problem.

So I need to make code that checks if a user inputted value is in an array. So what I've got so far is:

import java.util.Scanner; public class array1 { public static void main(String[]args) { int [] arraynumbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; Scanner sc = new Scanner(System.in); System.out.println("Enter a value"); int num = sc.nextInt(); } } 

This is what I've got so far, and I have no idea how to check if this value exists in the array I created. I had checked other results but could not find one that was in my learning range.

So is there a way to check if a value stated by a user exists in an array?

3
  • 2
    iterate the array and compare with num . Commented Feb 25, 2016 at 3:51
  • for primitive types there's no option other than iterating, make it a generic instead Commented Feb 25, 2016 at 3:52
  • Try 'Arrays.binarySearch(array, searchkey)' it will return index of the element if found Commented Feb 25, 2016 at 3:54

10 Answers 10

1

One way to do it is using a for loop:

//conventional for loop for (int i = 0; i < arraynumbers.length; i++) { if (arraynumbers[i] == num) System.out.print(num + " found!"); } //"for each" loop for (int number : arraynumbers) { if (number == num) System.out.print(num + " found!"); } 
Sign up to request clarification or add additional context in comments.

Comments

1

What would you do, programming set aside, with a paper and a pen, to perform that operation manually? Considering that the list can be much bigger than 10 elements, you need a systematic approach.

You would probably look at each element of the list, one after the other, and compare that element with the number you are looking for.

Looking at each element of a list is what a loop does.

Testing and comparing usually involves relational operators, like ==, or <

So, you need to loop through all the elements, compare them with the value you are looking for using the right operator, and test the result of that comparison:

for (int value: arraynumbers) { if (value == num) { // Here you found the number you are looking for } } 

Comments

0
System.out.println(boolean found = Arrays.stream(arraynumbers).anyMatch(xh -> xh == num )); 

output:True

I am trying to keep Line of codes less.Hope My work helps.Happy coding.

Comments

0

Like this. This worked. Might give it a try.

import java.util.Scanner; public class array1 { public static void main(String[] args) { int[] arraynumbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; Scanner sc = new Scanner(System.in); System.out.println("Enter a value"); int num = sc.nextInt(); for (int x = 0; x < arraynumbers.length; x++) { if (arraynumbers[x] == num) { System.out.println("Value exists in array!"); }else{ System.out.println("Value doesn't exists in array!"); } } } } 

Comments

0

I would use an enhanced for loop

public static bool findNum() { int [] arraynumbers = {1,2,3,4,5,6,7,8,9,10}; Scanner sc = new Scanner(System.in); System.out.println("Enter a value: "); int num = sc.nextInt(); boolean found = false; for (int i : arraynumbers) { if (num == i) { found = true; } } return found; } 

Basically, the enhanced for loop does the following:
Initializes an int i
Moves through the arraynumbers array one element at a time, storing the array item in the i
If the input is equal to the current array item, found is set to true
The method then returns the value of true

I like the syntax of the Java enhanced for loop more than other languages, but for a beginner, it might be a little hard to understand. Think of it like this: starting at the first element in the array, represent that item with the label 'i', test if that item is equal to the input and if so, set the value of found to true.
Using array.length in a for loop is fine too, but this is a lot less to type and in larger applications will help with load speed.

Comments

0

I made a very clear solution based on Java 8 Lambda Expressions.

Arrays.stream(arraynumbers).filter(x -> x == num).forEach(System.out::println);

I made a little demonstration, you can test here: Ideone

Comments

0

If you would like to include where you found the item in your array (the index), you could loop through the array, make a condition that terminates once the user number is found, and prints the number and its respective index.

If you haven't learned this yet, arrays are indexed starting at zero. So, if your array is

 {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} 

then the indices are

 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 import java.util.Scanner; public class Array1 { public static void main(String[] args) { int[] arrayNumbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; Scanner sc = new Scanner(System.in); System.out.print("Enter a value: "); int num = sc.nextInt(); boolean match = false; for (int i = 0; i < arrayNumbers.length; i++) { if (num == arrayNumbers[i]) { //you're checking if your user's 'num' is the same as a certain number in the array with the '==' operator match = true; //assign your boolean to true since it's found System.out.println("Found " + num + " at index " + i + "!"); //print their number and the index break; //no need to loop through the entire array. if you keep going with programming, you'll learn about efficiency more in depth down the road. :) } } if(!match) { //Keep this outside the for loop, otherwise it will print this statement arrayNumbers.length number of times, in this case 10 times. System.out.println("Did not find " + num + " in the array."); } } } 

The output for correct and incorrect user input:

 Enter a value: 7 Found 7 at index 6! //see how it gives the index? Enter a value: 45 Did not find 45 in the array. //only prints once since it wasn't in the for loop. 

Comments

0

Probably the most concise way of doing it using the code snippet below.

boolean exist = Arrays.asList(new String[]{"value1", "value2", "value3"}).contains("value3"); 

or

String[] validValues={"value1", "value2", "value3"}; boolean exist = Arrays.asList(validValues).contains("value3"); 

Comments

0
public static void main(String[] args) { int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; Scanner sc = new Scanner(System.in); System.out.println("Enter a value :"); int num = sc.nextInt(); if(Arrays.stream(numbers).filter(l -> l == num).findFirst().isPresent()){ System.out.println("Entered number is present in the array."); }else { System.out.println("Entered number is NOT present in the array."); } } 

1 Comment

while this code may answer the question, it is better to explain how it works and how it solves the problem. As it stands, this is unlikely to help future visitors.
0

You should use a proper data structure. In case you want to check if value exists or not, you should use Set.

public class array1 { public static void main(String[]args) { Set<Integet> numbers = Set.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); Scanner sc = new Scanner(System.in); System.out.println("Enter a value"); int num = sc.nextInt(); boolean exists = numbers.contains(num); } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.