java - 程序只会输出else语句

标签 java arrays if-statement while-loop stdin

我正在使用普林斯顿大学的 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/

相关文章:

c++ - 解析计算器的这段代码有什么问题?

java - 为什么我的 ImageView (Android Studio) 的图像仅在 onClick-Method 结束时发生变化?

javascript - 在 Javascript 中调用对象方法

javascript - 在JS中每秒旋转数组中元素的位置

c++ - C++ 字符串和字符串 vector 的 C 实现

string - 在 Bash 中比较两个字符串时出现 "command not found"错误

java - 使用 twitter4j 和 java 获取所有用户时间线推文

java - 需要编写一个 java 正则表达式,该表达式与 http 或 https 的 url 匹配,但不包含特定的文件扩展名

java - JPA - 无法获取在一对一关系中生成的主键

带有某些 IF ELSE If ELSE 条件的 Mysql 查询