Java

时间:2019-03-09 13:20:34

标签: java object-oriented-analysis abstract-data-type linear-search

我是Java编程的新手,并获得了要执行的任务。该程序是用伪代码编写的。这是到目前为止我已经能够开发的东西,但是我一直收到错误消息。请帮助我完成线性搜索摘要数据类型的实现。

谢谢。

import java.util.Scanner; 

public class LinearSearch {
private int [] Arr;

/* constructor*/
public LinearSearch(int s) {
    this.Arr = new int [s]; 
}



/* toString method which shows the elements of the array as a string.*/
public String toString() {
    StringBuilder sb = new StringBuilder() ;
    for (int i : this.Arr) {
        sb.append(i).append(", ");
    }   

    return sb.toString();
}

public int search(int y) { 
    //y is value to be searched. 
    int i = 0; //location of y in the array

    int v; // value to be returned after search.
    while (i < Arr.length && Arr[i] != y) {

        if (Arr[i] == y) {
            i++;
            v = i;
            return v;
        } else {
            v = -1;
            return v;
        }

    }
    return i;       
}

public static void main(String[] args) {
    /*Creating an object "linS" of the class. */
    LinearSearch linS = new LinearSearch(10);

    //creating an array of random values from 1 to 100;
    for (int i = 0; i < Arr.length; i++) { 
        Arr[i] = (int)(Math.random()*100) + 1;  
    }



    Scanner input = new Scanner(System.in);
    System.out.print("Input value to be searched: ");
    int x = input.nextInt(); //x stores the value to be searched.
    System.out.println("Array: " + linS.toString());
    System.out.println("Search index: " + linS.search(x));
}

}

0 个答案:

没有答案