2016-05-11 116 views
-1
import java.util.HashSet; 
import java.util.Scanner; 
public class HashSetExample { 
public static void main(String[] args) 
{ 
    System.out.println("Enter the number of Entries"); 
    Scanner sc =new Scanner(System.in); 
    int i=sc.nextInt(); 
    HashSet<String> hs=new HashSet<String>(); 
    System.out.println("Enter the Entries, > to quit"); 
    Scanner scr =new Scanner(System.in); 
    for(int j=0;j<i;j++) { 
     String s=scr.nextLine(); 

     if (s.equals(">")) { 
      break; 
     } else { 
      hs.add(s); 
     } 

     for(String str:hs) { 
      System.out.println("The Entries are" + str); 
     } 
    } 
} 

在上述程序中,首先要求用戶輸入條目數。如果用戶輸入10,則控制檯應該提示輸入10次。如果在輸入5個條目之後用戶按下>按鈕,程序應該終止並顯示迄今爲止輸入的條目。但由於某些邏輯錯誤,程序在輸入第一個條目後終止並僅顯示第一個條目。輸出是:HashSet()邏輯錯誤

Enter the number of Entries 
10 
Enter the Entries, > to quit 
Paul 
The Entries arePaul 
+1

你的代碼工作正常,我。只需將最後一個循環放置在外部循環之外,以在插入完成後打印結果。 *友好提醒*:修復您的縮進! – Lefteris008

+0

[什麼是調試器,它如何幫助我診斷問題]可能的重複(http://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me -diagnose-問題) – Raedwald

回答

0

將您的打印迴路輸入迴路之外:

for(int j = 0; j < i; j++) { 
    String s = scr.nextLine(); 
    if (s.equals(">")) { 
     break; 
    } else { 
     hs.add(s); 
    } 
} 

for (String str : hs) {// print loop 
    System.out.println("The Entries are " + str); 
}