簡體   English   中英

HashSet() 邏輯錯誤

[英]HashSet() Logical error

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,則控制台應提示輸入 Entries 十次。 如果用戶在輸入 5 個條目后按下 > 按鈕,程序應終止並顯示到目前為止輸入的條目。 但是由於一些邏輯錯誤,程序在輸入第一個條目后終止,只顯示第一個條目。 輸出是:

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

將打印循環放在輸入循環之外:

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

暫無
暫無

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

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