顺序搜索算法

0 java arrays

大家好,我在为二维int数组创建顺序搜索算法时遇到了麻烦.我不确定如何去扩充while循环所以它的工作原理,我正在使用的例子确实是我写出来的,因为你可以看到我的编译器抱怨与其写出的方式不兼容!

  import java.util.*;
      import javax.swing.*;
      public class pencilneck
  {
    public static void main(String []alex)
  {
  int ROWS = 6;
  int COLS = 3;
  int[][] chargeAcc = new int[ROWS][COLS];
  Scanner keyboard = new Scanner(System.in);

  for(int row = 0; row < ROWS; row++)
     {
        for(int col = 0; col < COLS; col++)
        {
           System.out.print("Enter Account");
           chargeAcc[row][col] = keyboard.nextInt();
        }
     }

     System.out.print("Enter an account to be Charged");
     int input = keyboard.nextInt();
     int results = SequentialSearch(chargeAcc,input);

     if(results ==-1)
     {
        System.out.println("that is an invalid #");
     }
     else
     {
        System.out.println("the # is valid");
     }
Run Code Online (Sandbox Code Playgroud)

}

  public static int SequentialSearch(int[][] array, int value)
  {
     int index1 = 0;
     int element = -1;
     boolean found = false;

        while(!found && index1 == value)
        {
           if(array[index] == value)
           {
              found = true;
              element = index;
           }
           index++;

        }
     return element;
  } 
Run Code Online (Sandbox Code Playgroud)

}

ihe*_*nyi 5

你的问题没有多大意义,但代码中的错误很容易找到.

while(!found && index1 == value)
Run Code Online (Sandbox Code Playgroud)

这用简单的英语说,在循环中做这些东西,而这些条件都是正确的:

  1. 发现是假的
  2. index(数组索引)等于value(要在数组中查找的数字)

在循环开始时,index == 0.由于value可能非零,因此第二个条件为false且循环永远不会运行,导致SequentialSearch立即返回-1.

既然你知道问题是什么,我会留给你花时间去理解你做错了什么,并弄清楚如何解决它.