【问题标题】:Why use empty string in Linear Search Java program为什么在线性搜索 Java 程序中使用空字符串
【发布时间】:2016-10-19 06:02:47
【问题描述】:

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

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 + " "。我不明白做这两件事的目的。

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

输出:

【问题讨论】:

    标签: arrays string algorithm data-structures linear-search


    【解决方案1】:

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

    indexsWithValue+= i + " ";
    

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

    你的输出会是这样的。

    i1 i2 i3 ....

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

    【讨论】:

      【解决方案2】:

      你不需要它。 在您的代码中,当您在数组中没有提供的键时,结果为“无”。

      因此,您默认将其声明为字符串。

      【讨论】:

      • 为什么是 indexsWithValue+= i + " " 而不是 indexsWithValue= i + " " ?
      • 如果提供的数组中的键出现不止一次!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-21
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多