bài 7

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.8 kB
0
Indexable
Never
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package s00007;

import java.util.Random;
import java.util.Scanner;

/**
 *
 * @author MSI GTX
 */
public class LinearSearch {

    private int a[];
    private int n;
    private int f;
    Scanner sc = new Scanner(System.in);

    /**
     * Enter the value N random value of N
     */
    public void Scanner() {
        System.out.println("Enter number of array: ");
        boolean b = true;
        while (b) {
            try {
                n = Integer.parseInt(sc.nextLine());
                if (n >= 2) {
                    b = false;
                    a = new int[n];
                } else {
                    System.out.println("Error: The value of the array must be greater than 2 ");
                    System.out.println("Enter number of array: ");
                }
            } //If the user enters a character, input again
            catch (NumberFormatException e) {
                System.out.println("Accept only number!");
                System.out.println("Enter number of array: ");
            }

        }
        System.out.println("Enter search value:");
        f = sc.nextInt();
    }

    /**
     * Random values of N
     */
    public void random() {
        for (int i = 0; i < a.length; i++) {
            Random rand = new Random();
            a[i] = rand.nextInt(100) + 1;
        }
    }

    /**
     * Use LinearSearch to find the value to look for
     *
     * @param key
     * @return
     */
    public int linearSearch(int key) {
        key = f;
        for (int i = 0; i < n; i++) {
            if (a[i] == key) {
                return i;
            }
        }
        return -1;
    }

    /**
     * Show search value or report not found
     */
    public void show() {
        System.out.println("The array: " + toString());
        int result = linearSearch(f);
        if (result == -1) {
            System.out.println("That searched value doesn't present in the array.");
        } else {
            System.out.println("Found " + f + " at index: " + result);
        }

    }

    /**
     * Print array after random
     *
     * @return
     */
    @Override
    public String toString() {
        String str = "";           //Create empty string
        str += "[";
        for (int i = 0; i < a.length; i++) {
            if (i != a.length - 1) {
                str += a[i] + ", ";
            } else {
                str += a[i];
            }
        }
        str += "]";
        return str;
    }
}