【发布时间】:2017-06-05 07:25:53
【问题描述】:
我正在使用 Princeton 的 StdIn 库在 Java 中创建线性搜索,但我不明白为什么我的 if-else 语句只会打印出“-1”。
在我看来,它完全跳过了if 块并直接进入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 的值。现在的问题是ArrayList 仅填充到我输入的第一个数字时,我需要填充到命令行参数中输入的许多ints
【问题讨论】:
-
使用调试器找出来
-
@Jens 我该怎么做?抱歉,我对一般编程很陌生
-
使用谷歌了解如何做到这一点
-
你用的是什么IDE?
-
@SteveSmith 我正在使用 DrJava
标签: java arrays if-statement while-loop stdin