我正在使用普林斯顿大学的 StdIn 库在 Java 中创建线性搜索,但我不明白为什么我的 if-else
语句只会打印出“-1”。
在我看来,它完全跳过了 if
block ,直接进入 else
。我正在使用命令行参数输入列表,并通过按 control-d 结束列表(不确定 Windows 上的是什么,抱歉)。任何帮助将不胜感激。
public class SearchAlgs {
public static void main(String[] args) {
if (args[0].equals("linear")) {
int n = Integer.parseInt(args[1]);
LinearSearch(n);
}
else {
System.out.println("Please enter linear");
}
}
public static void LinearSearch(int n) {
int x = -1;
//int u = -1;
int c, search, array[];
int value = StdIn.readInt(); //input values
array = new int[value]; //array list
while (x < 0) {
//System.out.println(n);
//System.out.println("linear");
//loop to populate array list
for(c = 0; c < value; c++)
array[c] = StdIn.readInt();
//loop to search for "n"
for (c = 0; c < value; c++) {
if(array[c] == n){
System.out.println(n + " is at index " + c);
x++;
return;
}
else{
continue;
}
}
System.out.println("-1");
x++;
}
}
}
编辑:
我更新了整个 LinearSearch(n)
方法。现在,它从我输入的列表中查找值,并在该值不存在时为我提供 -1
值。现在的问题是,当我需要填充到命令行参数中输入的任意多个 int 时,ArrayList 只会填充到我输入的第一个数字。/p>
最佳答案
只要搜索到的值不在数组中,您的方法就会返回(打印 -1 后):
else{
System.out.println("-1");
return; // EXITING HERE
}
因此,如果输入的值不是数组中的第一个值,您将得到 -1 并且该方法终止。
您可能想要的是在找到值后立即返回(打印后),或者继续搜索到最后一个数组条目。当这个循环存在后,即没有找到任何东西,你想打印-1(并返回/终止)。
类似于
loop array {
if value is equal array entry {
print message
return
}
// else continue looping
}
print -1
关于java - 程序只会输出else语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41761401/