Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 为什么在线性搜索Java程序中使用空字符串_Arrays_String_Algorithm_Data Structures_Linear Search - Fatal编程技术网

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

Arrays 为什么在线性搜索Java程序中使用空字符串,arrays,string,algorithm,data-structures,linear-search,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++) {

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

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] + " ");

}
private int[]theArray=new int[50];
私有int-arraySize=10;
公共字符串linearSearchForValue(int值){
布尔值inarray=false;
字符串索引WithValue=“”;
for(int i=0;i
在linearSearchForValue方法中,将
IndexWithValue
设置为空字符串的目的是什么。在if语句中
IndexWithValue+=i+“”;
将空字符串添加到
i+“”
。我不理解执行这两项操作的目的

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


输出:

您不需要它。它只是用于输出

indexsWithValue+= i + " ";
确保连接所有匹配的索引

您的输出将如下所示

i1 i2 i3

其中i1、i2……是找到的匹配项。

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


因此,默认情况下将其声明为字符串。

为什么它是IndexWithValue+=i+“”,而不是IndexWithValue=i+“”?因为在提供的数组中是否出现了多个键!