【问题标题】:java: HashSet to show error message on inputing duplicate Integer valuesjava: HashSet 在输入重复整数值时显示错误消息
【发布时间】:2015-09-11 02:08:13
【问题描述】:

我必须编写一个程序,允许用户输入 10 个整数,并在每次用户输入以前使用 HashSet 输入的整数时显示错误消息。 到目前为止,我已经想出了这个,但问题是每次输入数字时都会出现错误消息。

package lesson1;
import java.util.*;

public class MyClass1{

public static void main(String[] args) {

    Set<Integer> h= new HashSet<Integer>();

    Scanner input= new Scanner(System.in);

    for(int i=0; i<10;i++){

        Object s=h.add(input.nextInt());

        if(s!=null){

            System.out.println("Duplicates are not allowed");
        }

    }


    System.out.println(h);


      }

}

【问题讨论】:

    标签: java duplicates hashset


    【解决方案1】:

    Set.add 如果元素存在则返回真,否则返回假。您正在检查结果是否为空。您需要将代码更改为:

        boolean nonDuplicate = h.add(input.nextInt());
        if(!nonDuplicate) {
           System.out.println("Duplicates are not allowed");
           // ...
    

    【讨论】:

      【解决方案2】:

      其实朋友你下面的条件是错误的

       Object s=h.add(input.nextInt());
      
          if(s!=null){
      
                      System.out.println("Duplicates are not allowed");
                  }
      

      你必须用

      替换它
      boolean s=h.add(input.nextInt());
      
              if(!s){
      
                      System.out.println("Duplicates are not allowed");
                  }
      

      【讨论】:

        【解决方案3】:
        import java.io.*;
        import java.util.*;
        import java.lang.*;
        
        public class mainactivity {
        public static void main(String a[]) {
            Set<Integer> h = new HashSet<Integer>();
        
            Scanner input = new Scanner(System.in);
        
            for (int i = 0; i < 3; i++) {
        
                boolean check = h.add(input.nextInt());
        
                if (!check) {
        
                    System.out.println("already exist");
                }
            }
            System.out.println(h);
        
        }
        }
        

        这是工作代码

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-03-13
          • 2014-09-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多