猿问

在存储在哈希集中的生成代码中查找单词

示例生成代码:910love009tre


我想检查生成的代码中是否有特定的单词。我正在尝试使用contains-method,但它似乎没有给我所需的输出。


import java.security.SecureRandom;

import java.util.HashSet;

import java.util.Set;


public class AlphaNumericExample {

  public static void main(String[] args) {


    enter code here

    AlphaNumericExample example = new AlphaNumericExample();

    Set<String> codes = new HashSet<>();

    for (int x = 0;x< 100 ;x++ ) {


       codes.add(example.getAlphaNumeric(16));

    System.out.println(codes.contains("love"));//Im trying to check if the generated codes that have been stored in hashset have form a word 

    }


    System.out.println("Size of the set: "+codes.size());



  }


  public String getAlphaNumeric(int len) {


    char[] ch = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();


    char[] c = new char[len];

    SecureRandom random = new SecureRandom();//

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

      c[i] = ch[random.nextInt(ch.length)];

    }


    return new String(c);

  }

}


莫回无
浏览 152回答 3
3回答

哈士奇WWW

在这种情况下, contains 方法检查整个对象是否匹配。如果它包含特定的字符序列,则不会,因此 13 个字符的对象永远不会匹配 4 个字母的序列代替System.out.println(codes.contains("love"));//Im trying to check if the generated codes that have been stored in hashset have form a word&nbsp;在每个单独的字符串上尝试 contains 方法,而不是 HashSet 的 contains 方法for (String code: codes) {&nbsp;&nbsp; &nbsp; if&nbsp; (code.contains("love")&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp;System.out.println("found!")&nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; }}

慕标5832272

像这样使用它for (int x = 0; x < 100; x++) {&nbsp; &nbsp; String generated = example.getAlphaNumeric(16);&nbsp; &nbsp; codes.add(generated);&nbsp; &nbsp; System.out.println(generated.contains("love"));}

守候你守候我

您正在检查代码集中的完整字符串“love”。您需要在代码集中的每个代码中检查它是否存在。您可以使用流来检查这一点。boolean&nbsp;isPresent&nbsp;=&nbsp;codes.stream().anyMatch(&nbsp;code&nbsp;->&nbsp;code.indexOf(&nbsp;"love"&nbsp;)&nbsp;!=&nbsp;-1&nbsp;);
随时随地看视频慕课网APP

相关分类

Java
我要回答