数组搜索元素的问题

时间:2014-04-27 22:28:28

标签: java arrays

我一直在尝试使用用户输入的值搜索数组。例如,如果用户想要在数组中搜索数字10,它将找到元素10的位置并将其打印出来。我不知道我做错了什么。请帮我。谢谢。

这就是我所拥有的:

import java.util.Arrays;
import java.lang.Object.*;
import java.util.Scanner;


public class DeleteElements {


  public static void main(String[] args) { 
    Scanner input = new Scanner(System.in);
    int del = 0;
    boolean check;
    int intArray[] = {10,20,30,40,50};

    System.out.print("The array consists of: ");
    for (int i = 0; i < intArray.length; i++) {
      System.out.print(intArray[i] + ", ");
    }

    System.out.print("\nWhich number should be removed for the list? ");
    del = input.nextInt();
    System.out.println("Number to delete: " + del);

    if(intArray.length == del){
      check = true;
      System.out.println("Good");
    }else{ 
      check = false;
      System.out.println("Bad");
    }

    while (check == true){
      for(int i = 0; i < intArray.length; i++){
        if (intArray[i] == del){
          System.out.println("Number found at index: " + i);
        }
      }
      System.out.println("Number not found!");
    }
  }
}

4 个答案:

答案 0 :(得分:0)

问题是您的代码永远不会离开while(check == true)语句。我会删除数组长度检查if语句,因为它是多余的。当你执行for(int i=0; i < intArray.lenght; i++)时,你已经确定你不会检查出界限。此外:为什么要检查输入是否等于数组长度?

答案 1 :(得分:0)

您需要删除此

  if(intArray.length == del){
      check = true;
      System.out.println("Good");
    }else{ 
      check = false;
      System.out.println("Bad");
    }

然后把它放在

之后
 for(int i = 0; i < intArray.length; i++){
    if (intArray[i] == del){
      System.out.println("Number found at index: " + i);
    }
  }
  System.out.println("Number not found!");

所以完整的实现应该是:

import java.util.Arrays;
import java.lang.Object.*;
import java.util.Scanner;


public class DeleteElements {


  public static void main(String[] args) { 
    Scanner input = new Scanner(System.in);
    int del = 0;
    int intArray[] = {10,20,30,40,50};

    System.out.print("The array consists of: ");
    for (int i = 0; i < intArray.length; i++) {
      System.out.print(intArray[i] + ", ");
    }

    System.out.print("\nWhich number should be removed for the list? ");
    del = input.nextInt();
    System.out.println("Number to delete: " + del);



      for(int i = 0; i < intArray.length; i++){
        if (intArray[i] == del){
          System.out.println("Number found at index: " + i);
        }
      }
      System.out.println("Number not found!");

  }
}

答案 2 :(得分:0)

for (int i = 0; i < intArray.length; i++) {
if (intArray[i] == del) {
System.out.println("You found that number");
}
}

答案 3 :(得分:0)

我不确定你要检查的是什么:

if(intArray.length == del){
  check = true;
  System.out.println("Good");
}else{ 
  check = false;
  System.out.println("Bad");
}

但我认为你不需要它

条件     intArray.length == del 这个例子总是假的,所以你不能在所有的

进入循环