gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:41:17 27 4
gpt4 key购买 nike

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

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com