I was wondering if there is a way in java to pull and integer found at a specific index in an array. I then want to store that integer in a variable. Is this something that can be done?
3 Answers
You can easily find an integer found at a specified index in an array. There are multiple ways to achieve this.
Code:
**import java.util.Scanner;
public class FindElementInArray
{
public static void main(String[] args)
{
int n, x, flag = 0, i = 0;
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array:");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter all the elements:");
for(i = 0; i < n; i++)
{
a[i] = s.nextInt();
}
System.out.print("Enter the element you want to find:");
x = s.nextInt();
for(i = 0; i < n; i++)
{
if(a[i] == x)
{
flag = 1;
break;
}
else
{
flag = 0;
}
}
if(flag == 1)
{
System.out.println("Element found at position:"+(i + 1));
}
else
{
System.out.println("Element not found");
}
}
}**
1 Comment
Spencer Colón
Thanks for the help, I'm going to look over this!