summary refs log blame commit diff stats
path: root/java/code/FindNumberInArray.java
blob: 2bf7f1a1ae155a6be5d731f979eca4dc8e3a1c8f (plain) (tree)







































































                                                                                                                         
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");
        }
    }
}