我有一个用Java进行二进制搜索的程序.在为数组输入后,'for-each'循环似乎没有增加计数器变量.但是,它确实适用于常规的'for'循环.为什么'for-each'循环在这种情况下不能增加计数器?
import java.util.Scanner;
public class binarySearch {
public static int rank(int key, int[] a) {
int lo = 0;
int hi = a.length - 1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (key > a[mid])
lo = mid + 1;
else if (key < a[mid])
hi = mid - 1;
else
return mid;
}
return -1;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the key to be searched");
int key = in.nextInt();
System.out.println("\nEnter the number of elements in the array");
int num = in.nextInt();
int[] array = new int[num];
for (int counter : array) {
System.out.println("Enter the element of the array!");
array[counter] = in.nextInt();
}
int result = rank(key, array);
if (result == -1) {
System.out.println("\n The given key is not found!\n");
} else {
System.out.println("\n The given key is found at position : " + (result + 1));
}
}
}
Run Code Online (Sandbox Code Playgroud)
你刚刚创建了数组而没有填充它,所以它将充满默认值.然后,您将迭代数组元素的值,这意味着counter每次的值都将为0.这个循环:
for(int counter : array )
{
System.out.println("Enter the element of the array!");
array[counter] = in.nextInt();
}
Run Code Online (Sandbox Code Playgroud)
......大致相当于:
for (int i = 0; i < array.length; i++) {
// Note: this will always be zero because the array elements are all zero to start with
int counter = array[i];
System.out.println("Enter the element of the array!");
array[counter] = in.nextInt();
}
Run Code Online (Sandbox Code Playgroud)
你根本不想迭代数组中的原始值 - 你只想迭代从0到数组的长度(独占),这很容易用for循环完成:
for (int i = 0; i < array.length; i++) {
System.out.println("Enter the element of the array!");
array[i] = in.nextInt();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
115 次 |
| 最近记录: |