簡體   English   中英

如何退出此循環?

[英]How can I exit out of this loop?

此代碼試圖接受用戶的密鑰並將其存儲到字符串數據數組中。 在程序的后面,每個鍵的值以某種特定格式顯示。

首先,我希望當用戶輸入為空/下一行時此循環結束/退出。 我不想使用任何EOF字符或字符串退出循環。

我對以前的SO問題/解決方案進行了一些搜索,但在我的情況下不起作用。 需要幫助解決此問題,或者歡迎其他任何替代方法。

提前致謝!

class DictionaryAndMap{
  public static void main(String[] args){
    Scanner sc = new Scanner(System.in);
    int len = sc.nextInt();
    Map<String, Integer> mp = new HashMap<String, Integer>();
    String name;
    int phone;
    for(int i=0; i<len; i++){
      name = sc.next();
      phone = sc.nextInt();
      mp.put(name, phone);
    }
    int i=0;
    String arr1[] = new String[10];
    String nam;

// I couldn't exit out of this loop
   while(sc.hasNext()){
      nam = sc.next();
      if(nam!=null && !nam.trim().isEmpty()){
        arr1[i] = nam;
        i++;
      }
      else{
        break;
      }
    }

// iterating through the array to find the search inputs
    for(String j: arr1){
      if(mp.containsKey(arr1[j])){
        System.out.println(j+"="+mp.get(j));        
      }else{
        System.out.println("Not found");
      }
    }
  }
}

PS即使輸入為空/空/“”,hasNext()值也不會更改為false,因此while循環永遠不會結束。 如何使hasNext()檢測到那些空輸入數據中的任何一個,因此它可能退出循環?

閱讀輸入后,只需檢查輸入是否為空即可:

while (scanner.hasNextLine()) {
    nam = sc.nextLine();
    if (nam.trim().isEmpty())
         break;
    ...

然后,您可以通過僅用else替換else if並刪除最后一個else來簡化其余部分。

您必須檢查String是否為空或null中斷,以便控制從while循環中出來

nam=sc.next();
if(name==null || name.isEmpty()){
break; //break the loop 
}

我認為這是您正在尋找的代碼

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    String nam;
    Map<String, Objects> mp = new HashMap<>();
    String[] arr1 = new String[1024];
    int i = 0;
    nam = sc.nextLine();

    while (nam.length() > 0) {

        if (mp.containsKey(nam)) {
            arr1[i] = nam;
            i++;
        } else {
            System.out.println("Not found");
        }
        nam = sc.nextLine();
    }
}

通過使用空字符串敲回車將終止循環。

此代碼可以為您提供幫助。 您無需檢查!mp.containsKey(nm)

while(sc.hasNext()){
nam = sc.next();

if(mp.containsKey(nam)){
  arr1[i] = nam;
  i++;
}
else {
    System.out.println("Not found");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM