arrays - 为什么在线性搜索Java程序中使用空字符串

标签 arrays string algorithm data-structures linear-search

我正在使用以下方法对数组执行线性搜索:

private int[] theArray = new int[50]; 
private int arraySize = 10; 

public String linearSearchForValue(int value){

    boolean valueInArray = false;
    String indexsWithValue = "";

    for(int i = 0; i < arraySize; i++) {
        if(theArray[i] == value) {
            valueInArray = true;
            indexsWithValue+= i + " ";
        }
        printHorzArray(i, -1);
    }

    if(!valueInArray){
        indexsWithValue = "None";
    }

    System.out.print("The Value was Found in the Following: " + indexsWithValue);
    System.out.println();
    return indexsWithValue;
}

// Print Array
public void printHorzArray(int i, int j) {

for(int n = 0; n < 51; n++) {
    System.out.print("-");
}

System.out.println();

for(int n = 0; n < arraySize; n++) {
    System.out.print("| " + n + "  ");
}

System.out.println("|");

for(int n = 0; n < 51; n++) {
    System.out.print("-");
}

System.out.println();

for(int n = 0; n < arraySize; n++) {
System.out.print("| " + theArray[n] + " ");

}

在linearSearchForValue 方法中,将indexsWithValue 设置为空字符串的目的是什么。在 if 语句 indexsWithValue+= i + ""; 中,然后将空字符串添加到 i + ""。我不明白做这两件事的目的。

注意:数组元素是随机生成的。

输出:enter image description here

最佳答案

你不需要它。它只是为了输出。

indexsWithValue+= i + " ";

确保连接所有匹配的索引。

Your Output will be like.

i1 i2 i3 ....

其中 i1,i2,... 是找到的匹配项。

关于arrays - 为什么在线性搜索Java程序中使用空字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40123397/

相关文章:

regex - 正则表达式 :buffer same characters

python - 如何从 Python 中的路径获取不带扩展名的文件名?

algorithm - 需要帮助在二叉搜索树中的两个节点之间的路径中查找最大值

algorithm - 根据距离和方向创建坐标

c++ - 初始化 POD 数组中的第一个元素,保留其余元素未初始化

javascript - 平均二维数组中的连续值对

arrays - xcode、ios8、swift、文件和数组

javascript - 如何让 php `json_encode` 返回 Javascript 数组而不是 Javascript 对象?

sql - VB.NET : How to camel case words that are uppercased

algorithm - Dijkstra 算法 - 复杂度