如何在 else 之后执行一次打印(不使用中断)



我写了一些代码来模拟哈希。

如何在不使用break的情况下停止多次迭代并打印一次"未找到"?

主类:

public class hash {
    public static void main(String[] args) {
        contact[] table = new contact[88]; // Create an object of contact class
        int tablesize = 88;
        int Out = calc_hash("NAME", tablesize);
        table[Out] = new contact();
        table[Out].Name = "AHMED";
        table[Out].phone = 23445677;
        System.out.println(Out);
    }
}

我的问题在这里:

for (int i = 0; i < 36; i++) {
    if (table[i] != null) {
        if (table[i].Name != null) {
            System.out.println(i);
            System.out.println(table[i].Name);
            System.out.println(table[i].phone);
        }
    } else {
        System.out.println("Not found");
    } // Here "Not found" is printed with every iteration
}

哈希函数:

public static int calc_hash(String key, int table_size) {
    int i, l = key.length();
    int hash = 0;
    for (i = 0; i < l; i++) {
        hash += Character.getNumericValue(key.charAt(i));
        hash += (hash << 10);
        hash ^= (hash >> 6);
    }
    hash += (hash << 3);
    hash ^= (hash >> 11);
    hash += (hash << 15);
    if (hash > 0) return hash % table_size;
    else return -hash % table_size;
}
当您

处于else中时,您可以将i设置为 36

for  (int i = 0; i < 36  ; i++) 
   {
    if(table[i] !=null ) 
    {
        if (table [i].Name  != null) { 
        System.out.println(i); 
        System.out.println(table [i].Name);
        System.out.println(table [i].phone);}
    }
    else    
        { 
          System.out.println("Not found");
          i=36;
    } 
   }
    boolean notFound = false;    
    for  (int i = 0; i < 36  ; i++)
    {
        if(table[i] == null )
        {
           notFound = true;
            continue;
        }
        if (table [i].Name  != null) {
            System.out.println(i);
            System.out.println(table [i].Name);
            System.out.println(table [i].phone);}
    }
     if(notFound){
      System.out.println("Not found");
     }  // Here "Not found" is printed with every iteration

最新更新