在一组给定数据中,寻找确定的数据,线性查找。
package hello;
import java.util.Scanner;
public class Hello {
private static Scanner in;
public static void main(String[] args) {
// TODO Auto-generated method stub
in = new Scanner(System.in);
int[] data = {0,5,6,4,8,9,4,3,7};
int x = in.nextInt();
int loc = -1;
for (int i=0; i<data.length; i++)
{
if (x == data[i])
{
loc = i;
break;
}
}
if (loc > -1)
{
System.out.println(x+"是第"+(loc+1)+"个");
}
else
{
System.out.println(x+"不在其中");
}
}
}
如果只是确定数组中是否存在该变量,则可改写为for-each循环如下:
/*语法结构
for(<类型><变量>:<数组>)
{
...
}
*/
package hello;
import java.util.Scanner;
public class Hello {
private static Scanner in;
public static void main(String[] args) {
// TODO Auto-generated method stub
in = new Scanner(System.in);
int[] data = {0,5,6,4,8,9,4,3,7};
int x = in.nextInt();
boolean found = false;
for (int k:data)
{
if (k == x)
{
found = true;
System.out.println("存在");
}
}
}
}