# Problem with LinearArray

• September 10th, 2013, 09:14 AM
newbie_in_java
Problem with LinearArray
Welcome, people :)

I have a problem connected with LinearArray. I can search elements with this method but I have a problem with repeated elements. For example, I have elements 1 2 3 1. When I make my method it shows: " Your number is in position 0"? I want to do it with all positions

--- Update ---

I mean : " Number 1 is in position 0 , 3.
• September 10th, 2013, 09:40 AM
PhHein
Re: Problem with LinearArray
• September 10th, 2013, 09:11 PM
Junky
Re: Problem with LinearArray
Sounds like your code is stopping as soon as it finds a match. You need to keep searching the entire array.
• September 11th, 2013, 07:22 AM
newbie_in_java
Re: Problem with LinearArray
public class LinearArray {

private int data[];
private static Random generator = new Random();

public LinearArray(int size) {
data = new int[size];
for (int i = 0; i < size; i++) {
data[i] = 10 + generator.nextInt(91);
}
}

public int lineararray(int searchKey) {
for (int index = 0; index < data.length; index++) {
if (data[index] == searchKey) {
return index;
}
}
return -1;
}

public String toString() {
String temporary = "";
for (int element : data) {
temporary += element + " ";
}
temporary += " ";
return temporary;
}
}

--- Update ---

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

int searchInt;
int position;

LinearArray line = new LinearArray(10);
System.out.println(line);

System.out.print("Enter number(-1 to quit): ");
searchInt = input.nextInt();

while (searchInt != -1) {
position = line.lineararray(searchInt);
if (position == -1) {
System.out.println("The integer " + searchInt