关于变量公式在循环体外的错误
1 import java.util.Scanner; 2 public class TestArray { 3 4 public static void main(String[] args){ 5 int [] array = new int[]{13,24,35,56,77,89,90}; 6 Scanner input = new Scanner(System.in); 7 int i = input.nextInt(); 8 int start = 0; 9 int end = array.length-1; 10 int middle ;//此处middle,只申明变量,不赋值 11 int index = -1; 12 while(start<end){ 13 middle= (start+end)/2;//暂不清楚为什么只能在循环体内写入此公式,而不能在循环体外。 14 if(i==array[middle]){ 15 index = middle+1; 16 break; 17 } 18 if(i > array[middle]){ 19 start = middle+1; 20 } 21 if(i < array[middle]){ 22 end = middle-1; 23 } 24 } 25 26 if(index == -1){ 27 System.out.println("没找到"); 28 }else{ 29 System.out.println("在第"+index+"位"); 30 } 31 } 32 }