【问题标题】:How to find the position of a particular number inside an array? [duplicate]如何在数组中找到特定数字的位置? [复制]
【发布时间】:2018-03-01 11:54:21
【问题描述】:

如果我输入 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");
        }
    }
}

【问题讨论】:

  • 请删除javascript标签。
  • 那么,有什么问题?
  • 只要返回 i ,你就有位置了

标签: java


【解决方案1】:

首先,为了可测试性等目的,最好有这样的东西作为单独的函数。这也使代码更清晰。其次,如果您正在循环,您可能不想在循环内执行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));
        }
}

【讨论】:

  • 非常感谢......我得到了答案......
【解决方案2】:

只需使用下面的代码,它就会打印出预期的结果,如果您不希望数组考虑 0 位置,您可以随时在 'if' 条件内的输出语句中将 i 值增加到 i+1 '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");
            }

【讨论】:

    猜你喜欢
    • 2020-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多