Java Code Example: searchs an array for a number

This Java code searches for a number entered by the user in a given array of integers. The array is hard-coded and has the values: [65, 35, 23, 75, 76, 33, 12, 9]. The user is prompted to enter the number they are looking for.

The code uses a for loop to iterate over the elements of the array and check if the entered number matches any of the elements in the array. If a match is found, the boolean variable “numberInArray” is set to true, and the loop breaks.

After the loop, the code outputs whether the entered number was found in the array or not by using a ternary operator that checks the value of “numberInArray”. If it’s true, “found” is printed, and if it’s false, “not found” is printed.

import java.util.Scanner;

public class SearchNumberInArray {
	public static void main(String[] args) {
		Scanner reader = new Scanner(System.in);
		int number, i;
		boolean numberInArray = false;
		int numbers[] = {65, 35, 23, 75, 76, 33, 12, 9};

		System.out.print("What number are you looking for? " );
		number = reader.nextInt();
			
		// loop over array and search for number
		for(i = 0; i < numbers.length; i++) {
			if(number == numbers[i]) {
				numberInArray = true;
				break;
			}
		}
	
		// if boolean varible numberInArray is true ouput "found", 
		// if not output "not found"
		System.out.println("Number " + number + (numberInArray ? " found" : " not found") + " in Array!");
	}
}
Output
What number are you looking for? 9
Number 9 found in Array!