搜索:在一组给定的数据中,如何找出某个数据是否存在

import java.util.Scanner;
class S1
{
    int[] data = {2,4,3,5,7,9,6,8,12,13,34,52};
    Scanner in = new Scanner(System.in);
    public void show()
    {
        System.out.print("请输入要查找的数字在第几位:");
        int x = in.nextInt();
        int loc = -1;
        for(int i = 0 ; i<data.length ; i++)
        {

            if(data[i]==x)
            {
                loc = i;
                break;
            }
        }
        if( loc > -1)
        {
            System.out.println(x+"是第"+(loc+1)+"个");
        }
        else
        {
            System.out.println(x+"不在其中");
        }
    }
    public void show1()
    {
        int[] data = {2,4,5,7,22,55,12,3,5};
        System.out.print("请输入数据查询是否在数组中:");
        int x = in.nextInt();
        boolean found = false;
        for(int k:data)  //
        {
            if(x==k)
            {
                found = true;
                break;
            }
        }
        if(found)
        {
            System.out.print(x+"在其中");
        }
        else
        {
            System.out.print(x+"不在其中");
        }
    }
}
public class Seek {

    public static void main(String[] args) {
        // TODO 自动生成的方法存根
        S1 tow = new S1();
        tow.show();
        tow.show1();
    }

}
阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页