summary refs log tree commit diff stats
path: root/java/code/FindNumberInArray.java
blob: 2bf7f1a1ae155a6be5d731f979eca4dc8e3a1c8f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import java.util.Scanner;
import java.util.InputMismatchException;

class Number {
    private double value;
    Number(double n) {
        value = n;
    }
    double valueOf() {
        return value;
    }
    @Override
    public boolean equals(Object o) {
        if (o instanceof Number) {
            return value == ((Number)o).valueOf();
        }
        return false;
    } 
}

class NumberArray {
    Number[] array;
    NumberArray(double arr[]) {
        array = new Number[arr.length];
        for (int i = 0; i < arr.length; i++) {
            array[i] = new Number(arr[i]);
        }
    }
    int find(Number n) {
        for (int i = 0; i < array.length; i++) {
            if (array[i].equals(n)) {
                return i;
            }
        }
        return -1;
    }
    void display() {
        System.out.print("An array of numbers with " + array.length + " elements:");
        for (int i = 0; i < array.length; i++) {
            System.out.print(" " + array[i].valueOf());
        }
        System.out.println();
    }
}

class FindNumberInArray {
    public static void main(String args[]) {
        try {
            var sc = new Scanner(System.in);
            System.out.print("Enter length: ");
            var length = sc.nextInt();
            var arr = new double[length];
            System.out.print("Enter array elements: ");
            for (int i = 0; i < length; i++) {
                arr[i] = sc.nextDouble();
            }
            var narr = new NumberArray(arr);
            System.out.print("Given: ");
            narr.display();
            System.out.print("Enter element to find in array: ");
            var num = new Number(sc.nextDouble());
            var pos = narr.find(num);
            if (pos == -1) {
                System.out.println("Could not find the number " + num.valueOf() + " in the array.");
                return;
            }
            System.out.println("The number " + num.valueOf() + " was found in the array at position " + (pos + 1) + ".");
        } catch (InputMismatchException e) {
            System.err.println("Invalid number given as input");
        }
    }
}