Does not find specific number in array
I am trying to write a program that creates an array and fill it with int numbers(first method). In the end, it is supposed to see if a specific number is given in the array(second method). The problem is that the program does not run my if loops. I do not know why. The variable x is the number the program is looking for in the array and pos the position of the number in the array
public class Program {
static int [] numbers= new int[100];
public static void main(String [] args) {
PrintWriter out = new PrintWriter(System.out);
arrayConstruction();
test(out);
out.flush();
}
public static void arrayConstruction() {
int x = 0;
for (int i = 0; i < numbers.length; i++) {
numbers[i] = x;
x++;
}
}
public static void test(PrintWriter out) {
int x = 17;
int pos = 0;
if(pos != numbers.length) {
if(numbers[pos] == x) {
out.println("The number was found!");
out.flush();
}
pos++;
}
else if(pos == numbers.length) {
out.println("The number does not exist!");
out.flush();
}
}
}
You forgot to add a loop to the test method, so it checks the first array's item only. E.g. you can use while loop
.
public static void test(PrintWriter out) {
int x = 17;
int pos = 0;
while (true) {
if (pos != numbers.length) {
if (numbers[pos] == x) {
out.println("The number was found!");
return;
}
pos++;
} else if (pos == numbers.length) {
out.println("The number does not exist!");
return;
}
}
}
I think you should redesign your code by splitting different activities with separate methods. It makes your code clear to understand.
public class Main {
public static void main(String[] args) {
int[] arr = createArray(100);
System.out.println(isNumberExist(arr, 17) ? "The number was found!"
: "The number does not exist!");
}
public static int[] createArray(int total) {
int[] arr = new int[total];
Random random = new Random();
for (int i = 0; i < arr.length; i++)
arr[i] = random.nextInt(arr.length);
return arr;
}
public static boolean isNumberExist(int[] arr, int x) {
for (int i = 0; i < arr.length; i++)
if (arr[i] == x)
return true;
return false;
}
}