如何在数组中找到特定数字的位置?

时间:2017-09-20 12:10:33

标签: java

如果我输入98表示它将显示位置6.

public class OddEven {
    public static void main(String args[]) {
        int[] numbers = new int[] { 14, 23, 67, 10, 76, 5, 98, 13, 110 };
        for (int i = 0; i < numbers.length; i++) {
            if(numbers[i]==14)
                System.out.println(numbers[i]+"position 0");
            else 
                System.out.println(numbers[i]+"no. not in the list");
        }
    }
}

2 个答案:

答案 0 :(得分:0)

首先,将这样的东西作为可测试性等目的的单独功能是很好的。这也使代码更清晰。其次,如果您正在循环,您可能不希望在循环中执行system.out.println

所以你想要这样的东西:

public class IndexLookup {
    int[] numbers = new int[] { 14, 23, 67, 10, 76, 5, 98, 13, 110 };
    public int indexOf(int query) {
        for (int I = 0; I < numbers.length; i++) {
            if (numbers[I] == query){
                return I;
            }
        }
        return -1
    }
    public static void main(String[] args) {
        if (indexOf(98) == -1) {
            System.out.println("Not in list");
        } else {
            System.out.printf("Found %d at position %d%n", 98, indexOf(98));
        }
}

答案 1 :(得分:0)

只需使用下面的代码,它将打印预期的结果,如果你不希望数组考虑0位置,你总是可以将i值增加到i + 1 in out put语句里面的'if'条件'for'循环: - )

            boolean found = false;
            int[] numbers = { 14, 23, 67, 10, 76, 5, 98, 13, 110 };
            Scanner sc=new Scanner(System.in);  

            System.out.println("Enter the number to search");  
            int num =sc.nextInt();  
            for (int i = 0; i < numbers.length; i++) {
                if(numbers[i]==num){
                    System.out.println(numbers[i]+" position "+i);
                    found =true;
                    break;
                }
            }
            if(!found){
                System.out.println("Unable to find the Entered Number in the array");
            }