2016-05-11 7 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 - 糖尿病 - 問題) – Raedwald

答えて

0

置きますprintループを:

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); 
}