无法在Java中对数组进行二进制搜索

时间:2017-06-28 04:44:41

标签: java

目标

尝试二进制搜索数字数组的值。然后返回索引并将其更改为0.

代码:

import java.util.*;

public class Theater {

    static int [][] seats = {
        {10,10,10,10},
        {20,20,20,20},
        {30,30,30,30},
        {40,40,40,40}
        };

public static void main(String [] args)
{

    //These two for loops print the whole array.
for ( int i=0; i<4;i++)
{
    for (int j=0; j<4; j++)
    {
        System.out.print(seats[i][j] + " ");
    }
    System.out.println("");
}


   // entering the value to be searched
    Scanner ticketReq = new Scanner(System.in);
    System.out.println("Enter the ticket price you want: ");
    int ticketVal = ticketReq.nextInt();

   int indexOfTicket = Arrays.binarySearch(seats, ticketVal);

   if (indexOfTicket > 0) {
       System.out.println("The index of element 12 is : " + indexOfTicket + ". It is purchased!");
   }
   else {
       System.out.println("Tickets with price " + ticketVal + " are no longer available.");
   }


}

}// Ends the static void block

错误我有: Error

错误文字:

Exception in thread "main" java.lang.ClassCastException: [I cannot be cast to java.lang.Comparable
    at java.util.Arrays.binarySearch0(Unknown Source)
    at java.util.Arrays.binarySearch(Unknown Source)
    at Theater.main(Theater.java:31)

感谢任何帮助。是因为我有一个数组数组?有没有办法对数组数组进行二进制搜索?我真的想制作一个有4个座位(10,20,30,40)的剧院应用程序,并且用户输入货币价值,程序根据该值选择任意数量的座位。

2 个答案:

答案 0 :(得分:0)

在Java中,二维数组实际上是一维数组的数组。因此,您的搜索会尝试在数组中查找整数类型为integer的元素,从而导致类型错误,因为整数不是整数数组。

还有点不清楚你期望发生什么。二维数组中一个整数的位置如何用单个索引表示?

答案 1 :(得分:0)

在java中,Arrays.binarySerach(arr,element)适用于单维数组。因此,您需要通过将2-D数组转换为单维数组来处理您的情况,如下所示。

注意:它可能不符合您的要求,但您可以相应地考虑。

Scanner ticketReq = new Scanner(System.in);
        System.out.println("Enter the ticket price you want: ");
        int ticketVal = ticketReq.nextInt();
        int indexOfTicket =-1;
        for(int i=0;i<seats.length;i++){
            indexOfTicket = Arrays.binarySearch(seats[i], ticketVal);
        }

       if (indexOfTicket > 0) {
           System.out.println("The index of element 12 is : " + indexOfTicket + ". It is purchased!");
       }
       else {
           System.out.println("Tickets with price " + ticketVal + " are no longer available.");
       }