[英]java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0; why a[0][0] has ArrayIndexOutOfBoundsException problem?
[英]java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 7 on a binary search
我必须编写一个程序来通过输入“Prezzo”值来搜索“Nomi”的通讯员,但是当我进行二分搜索时,出现错误:
java.lang.ArrayIndexOutOfBoundsException:在二进制搜索中,长度为 7 的索引 -1 越界
这是代码:
import java.io.*;
public class Blackfriday {
public static int ricercaBinaria(Double prezzi[], Double chiave) {
int inf = 0, sup = prezzi.length - 1;
while (inf <= sup) {
int med = (inf + sup) / 2;
if (prezzi[med] == chiave)
return med;
if (prezzi[med] < chiave)
inf = med + 1;
else
sup = med - 1;
}
return -1;
}
public static void main(String args[]) {
try {
InputStreamReader isr;
BufferedReader br;
double cerca;
isr = new InputStreamReader(System.in);// abilitato la lettura da tastiera
br = new BufferedReader(isr);// abilitato la lettura un rigo per volta
String nomi[] = { "picones", "vinile di Speranza", "Laurea", "King Mufasa", "Pentium Gold",
"Aethey Wind breaker ORO", "HeelCompletoSpaic1we" };
Double prezzi[] = { 2.0, 13.50, 23.0, 99.50, 120.0, 75.20, 999.99 };
System.out.println("Quanto vuoi spendere?");
String xStringa = br.readLine();// ricevo la digitazione in String
cerca = Double.parseDouble(xStringa);// Trasformo la String in double
System.out.println("Puoi comprare: " + nomi[ricercaBinaria(prezzi, cerca)]);
} catch (Exception e) {
System.out.println(e);
}
}
}
您的代码至少有两个问题。
ricercaBinaria
一个前提是底层数据数组是有序的。 您在测试中使用了无序数据ricercaBinaria
将返回给定参数 ( Double
) 在您的数组中所在的索引。 如果未找到,则返回-1
。 因此,在将其用作索引数组之前,您需要检查返回的索引以验证它确实为正值 - 否则该方法将失败并出现您看到的异常这是一个功能代码:
public class Blackfriday {
public static int ricercaBinaria(double prezzi[], Double chiave) {
int inf = 0, sup = prezzi.length - 1;
while (inf <= sup) {
int med = (inf + sup) / 2;
if (prezzi[med] == chiave)
return med;
if (prezzi[med] < chiave)
inf = med + 1;
else
sup = med - 1;
}
return -1;
}
public static void main(String args[]) {
try {
InputStreamReader isr;
BufferedReader br;
double cerca;
isr = new InputStreamReader(System.in);//abilitato la lettura da tastiera
br = new BufferedReader(isr);//abilitato la lettura un rigo per volta
String nomi[] = {"picones", "vinile di Speranza", "Laurea", "King Mufasa", "Pentium Gold", "Aethey Wind breaker ORO", "HeelCompletoSpaic1we"};
double prezzi[] = {2.0, 13.50, 23.0, 99.50, 120.0, 75.20, 999.99};
System.out.println("Quanto vuoi spendere?");
String xStringa = br.readLine();//ricevo la digitazione in String
cerca = Double.parseDouble(xStringa);//Trasformo la String in double
System.out.println("Puoi comprare: " + nomi[ricercaBinaria(prezzi, cerca)]);
} catch (Exception e) {
e.printStackTrace();
}
}//main
}//classe
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.