我想搜索数组的特定元素,如果存在则返回其索引

时间:2016-01-15 21:39:08

标签: java arrays

我创建了一个类型为Savings的数组,其中包含String(Name)和double(帐号)。我想使用帐号进行搜索并查看它是否存在,然后返回包含这些元素的所有元素(名称+帐号)和数组的索引。我尝试了这个,但它不起作用。

import java.util.Arrays;
import java.util.Scanner;

public class Main {

    public static void main(String[] args){

        Savings[] ArrayOfSavings = new Savings[5];

        System.out.print("Enter Account Number: ");
        Scanner scan = new Scanner(System.in);
        double Ms = scan.nextDouble();

          //Loop until the length of the array
          for(int index = 0; index<= ArrayOfSavings.length;index++){

          if(ArrayOfSavings[index].equals(Ms)){

            //Print the index of the string on an array
            System.out.println("Found on index "+index);
             }
          }

        ArrayOfSavings[0] = new Savings("Giorgos",87654321);
        ArrayOfSavings[1] = new Savings("Panos",33667850);
    } 
}

/ 储蓄类 /

公共类储蓄延伸通用{

public Savings(String FN, double AN) {

    super(FN, AN);
}

@Override
 public String toString(){
     return String.format("Customer: %s \n Acount Number: %.1f,
             getFirstName(),getAccNumber();
 }

}

2 个答案:

答案 0 :(得分:0)

您可以执行以下操作:如果不存在,则返回-1;如果找到,则返回索引。只需要确保检查这种情况。

public static int findSavingsIfExists(double accountNumber, Savings[] allSavings) {
    for(int i = 0; i < allSavings.length(); i++) {
        if(allSavings[i].accountNumber == accountNumber) {
            return i;
        }
    }
    return -1;
}

并像这样使用

int index = findSavingsIfExists(..., ArrayOfSavings);
if(index != -1) {
    Savings foundSavings = ArrayOfSavings[index];
} else {
    //Not found
}

答案 1 :(得分:0)

尝试使用像这样的东西:

   double Ms = scan.nextDouble();
   int index = 0;
 for (int i = 0; i < ArrayOfSavings.length; i++) {
    if (ArrayOfSavings[i].getAccountNumber == Ms ) {
        index = i;
        break;
      }
  }

System.out.println(index);