Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Augmenting and structuring user queries to support efficient free-form code search

76 views

Published on

Presented at the 40th International Conference on Software Engineering, May 27 - 3 June 2018, Gothenburg, Sweden (ICSE 2018) as Journal first publication.

Published in: Software
  • Be the first to comment

  • Be the first to like this

Augmenting and structuring user queries to support efficient free-form code search

  1. 1. Augmenting and structuring user queries to support efficient free-form code search Raphael Sirres1, Tegawendé F. Bissyandé2, Dongsun Kim2, David Lo3, Kisub Kim2, Jacques Klein2, Yves Le Traon2 1 National Library of Luxembourg 2 Interdisciplinary Centre for Security, Reliability and Trust (SnT), University of Luxembourg 3 School of Information Systems, Singapore Management University 1.1 - logotype of the University of Luxembourg 3.1 - the Interdisciplinary Centre for Security Reliability and TrustJournal first-track paper; originally published in the Empirical Software Engineering Journal
  2. 2. Programming is always full of questions. - My code is correct? - How did other programmers implement? - Anything missing? - … 2
  3. 3. Programming is always full of questions. - My code is correct? - How did other programmers implement? - Anything missing? - … 2
  4. 4. Programming is always full of questions. - My code is correct? - How did other programmers implement? - Anything missing? - … 2
  5. 5. When you are learning a new language or library, - How to use this API? - Recommended implementations - Examples - … 3
  6. 6. First aid: Searching for code examples 4
  7. 7. First aid: Searching for code examples 4
  8. 8. First aid: Searching for code examples 4
  9. 9. First aid: Searching for code examples 4
  10. 10. "How do I invoke a Java method when given the method name as a string?" Let’s search for: 5
  11. 11. "How do I invoke a Java method when given the method name as a string?" Let’s search for: 6
  12. 12. "How do I invoke a Java method when given the method name as a string?" 6
  13. 13. "How do I invoke a Java method when given the method name as a string?" 7
  14. 14. "How do I invoke a Java method when given the method name as a string?" 7
  15. 15. "How do I invoke a Java method when given the method name as a string?" 8
  16. 16. "How do I invoke a Java method when given the method name as a string?" 9
  17. 17. "How do I invoke a Java method when given the method name as a string?" Java Clear All Filters Documents: MessageListenerAdapter.java Document type: Java Project: Spring Framework Author: Juergen Hoeller Date: Jul 09, 2014 292   * @see #buildListenerArguments 293   */ 294   protected Object invokeListenerMethod(String methodName, Object[] JMSException { 295   try { 296   MethodInvoker methodInvoker = new MethodInvoker(); MultiActionController.java Document type: Java Project: Spring Framework Author: Phillip Webb Date: Nov 22, 2013 0 214   * <p>Allows parameterization of handler method mappings. 215   */ 216   public final void setMethodNameResolver(MethodNameResolver method 217   this.methodNameResolver = methodNameResolver; 218   } NotifyBuilder.java Document type: Java Project: Apache­Camel Author: Claus Ibsen Date: Apr 10, 2013 06:17  676   return doWhenAnyMatches(predicate, false); 677   } 679   private NotifyBuilder doWhenAnyMatches(final Predicate predicate, received) { 680   stack.add(new EventPredicateSupport() { 681   private final AtomicBoolean matches = new AtomicBoolean(); SpelReproTests.java Document type: Java Project: Spring Framework Author: Juergen Hoeller Date: Dec 22, 201 413   /** Should be accessing Goo.getKey because 'bar' field evaluates  414   @Test 415 public void indexingAsAPropertyAccess SPR6968 1() { Check­in Comments Projects (22)  Apache­Hive (157)  Apache­Hbase (92)  IntelliJ IDEA Community Edition (72)  Apache Solr (41)  DataNucleus (18) Show more Document Types (12)  Java (455)  Plain (966)  JavaScript (159)  Html (40)  C++ (36) Show more Authors (35)  John Pullokkaran (131)  Aleksey Pivovarov (71)  zhangduo (48)  andy_jefferson (36)  Michael McCandless (33) 10
  18. 18. An experts may know it is “reflection”. Java Clear All Filters Documents: MessageListenerAdapter.java Document type: Java Project: Spring Framework Author: Juergen Hoeller Date: Jul 09, 2014 292   * @see #buildListenerArguments 293   */ 294   protected Object invokeListenerMethod(String methodName, Object[] JMSException { 295   try { 296   MethodInvoker methodInvoker = new MethodInvoker(); MultiActionController.java Document type: Java Project: Spring Framework Author: Phillip Webb Date: Nov 22, 2013 0 214   * <p>Allows parameterization of handler method mappings. 215   */ 216   public final void setMethodNameResolver(MethodNameResolver method 217   this.methodNameResolver = methodNameResolver; 218   } NotifyBuilder.java Document type: Java Project: Apache­Camel Author: Claus Ibsen Date: Apr 10, 2013 06:17  676   return doWhenAnyMatches(predicate, false); 677   } 679   private NotifyBuilder doWhenAnyMatches(final Predicate predicate, received) { 680   stack.add(new EventPredicateSupport() { 681   private final AtomicBoolean matches = new AtomicBoolean(); SpelReproTests.java Document type: Java Project: Spring Framework Author: Juergen Hoeller Date: Dec 22, 201 413   /** Should be accessing Goo.getKey because 'bar' field evaluates  414   @Test 415 public void indexingAsAPropertyAccess SPR6968 1() { Check­in Comments Projects (22)  Apache­Hive (157)  Apache­Hbase (92)  IntelliJ IDEA Community Edition (72)  Apache Solr (41)  DataNucleus (18) Show more Document Types (12)  Java (455)  Plain (966)  JavaScript (159)  Html (40)  C++ (36) Show more Authors (35)  John Pullokkaran (131)  Aleksey Pivovarov (71)  zhangduo (48)  andy_jefferson (36)  Michael McCandless (33) "How do I invoke a Java method when given the method name as a string?" 11
  19. 19. An experts may know it is “reflection”. Java Clear All Filters Documents: MessageListenerAdapter.java Document type: Java Project: Spring Framework Author: Juergen Hoeller Date: Jul 09, 2014 292   * @see #buildListenerArguments 293   */ 294   protected Object invokeListenerMethod(String methodName, Object[] JMSException { 295   try { 296   MethodInvoker methodInvoker = new MethodInvoker(); MultiActionController.java Document type: Java Project: Spring Framework Author: Phillip Webb Date: Nov 22, 2013 0 214   * <p>Allows parameterization of handler method mappings. 215   */ 216   public final void setMethodNameResolver(MethodNameResolver method 217   this.methodNameResolver = methodNameResolver; 218   } NotifyBuilder.java Document type: Java Project: Apache­Camel Author: Claus Ibsen Date: Apr 10, 2013 06:17  676   return doWhenAnyMatches(predicate, false); 677   } 679   private NotifyBuilder doWhenAnyMatches(final Predicate predicate, received) { 680   stack.add(new EventPredicateSupport() { 681   private final AtomicBoolean matches = new AtomicBoolean(); SpelReproTests.java Document type: Java Project: Spring Framework Author: Juergen Hoeller Date: Dec 22, 201 413   /** Should be accessing Goo.getKey because 'bar' field evaluates  414   @Test 415 public void indexingAsAPropertyAccess SPR6968 1() { Check­in Comments Projects (22)  Apache­Hive (157)  Apache­Hbase (92)  IntelliJ IDEA Community Edition (72)  Apache Solr (41)  DataNucleus (18) Show more Document Types (12)  Java (455)  Plain (966)  JavaScript (159)  Html (40)  C++ (36) Show more Authors (35)  John Pullokkaran (131)  Aleksey Pivovarov (71)  zhangduo (48)  andy_jefferson (36)  Michael McCandless (33) Report java reflection Advanced Search Browse Projects Java About 5010 search results for [java reflection] Clear All Filters Documents: 45   throw new UnsupportedOperationException(); ReflectionJoinpoint.java Document type: Java Project: WildFly Author: Ales Justin Date: Jul 25, 2011 09:52 PM 30   * @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a> 31   */ 32  public class ReflectionJoinpoint extends TargetJoinpoint { 33   private final BeanInfo beanInfo; 34   private final String methodName; ReflectionProvider.java Document type: Java Project: Terasology Author: Immortius Date: Jan 23, 2014 08:35 AM 41   * @author Immortius 42   */ 43  public class ReflectionProvider<T> implements PropertyProvider<T> { 44   private static final Logger logger = LoggerFactory.getLogger(ReflectionProvider.class); 46   private List<Property<T>> properties = Lists.newArrayList(); ReflectionReflectFactory.java Document type: Java Project: Terasology Author: Immortius Date: Jan 23, 2014 08:35 AM 30   * @author Immortius 31   */ 32  public class ReflectionReflectFactory implements ReflectFactory { Content Source Code and Documents Check­in Comments Projects (56)  DataNucleus (670)  SVN_SCMI_CLI_ performance (670)  IntelliJ IDEA Community Edition (610)  Apache­Hive (439)  Kotlin (294) Show more Document Types (19)  Java (5010)  Plain (1025)  XML (472)  Html (118)  JavaScript (108) Show more "How do I invoke a Java method when given the method name as a string?" 12
  20. 20. Java Clear All Filters Documents: MessageListenerAdapter.java Document type: Java Project: Spring Framework Author: Juergen Hoeller Date: Jul 09, 2014 292   * @see #buildListenerArguments 293   */ 294   protected Object invokeListenerMethod(String methodName, Object[] JMSException { 295   try { 296   MethodInvoker methodInvoker = new MethodInvoker(); MultiActionController.java Document type: Java Project: Spring Framework Author: Phillip Webb Date: Nov 22, 2013 0 214   * <p>Allows parameterization of handler method mappings. 215   */ 216   public final void setMethodNameResolver(MethodNameResolver method 217   this.methodNameResolver = methodNameResolver; 218   } NotifyBuilder.java Document type: Java Project: Apache­Camel Author: Claus Ibsen Date: Apr 10, 2013 06:17  676   return doWhenAnyMatches(predicate, false); 677   } 679   private NotifyBuilder doWhenAnyMatches(final Predicate predicate, received) { 680   stack.add(new EventPredicateSupport() { 681   private final AtomicBoolean matches = new AtomicBoolean(); SpelReproTests.java Document type: Java Project: Spring Framework Author: Juergen Hoeller Date: Dec 22, 201 413   /** Should be accessing Goo.getKey because 'bar' field evaluates  414   @Test 415 public void indexingAsAPropertyAccess SPR6968 1() { Check­in Comments Projects (22)  Apache­Hive (157)  Apache­Hbase (92)  IntelliJ IDEA Community Edition (72)  Apache Solr (41)  DataNucleus (18) Show more Document Types (12)  Java (455)  Plain (966)  JavaScript (159)  Html (40)  C++ (36) Show more Authors (35)  John Pullokkaran (131)  Aleksey Pivovarov (71)  zhangduo (48)  andy_jefferson (36)  Michael McCandless (33) Report java reflection Advanced Search Browse Projects Java About 5010 search results for [java reflection] Clear All Filters Documents: 45   throw new UnsupportedOperationException(); ReflectionJoinpoint.java Document type: Java Project: WildFly Author: Ales Justin Date: Jul 25, 2011 09:52 PM 30   * @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a> 31   */ 32  public class ReflectionJoinpoint extends TargetJoinpoint { 33   private final BeanInfo beanInfo; 34   private final String methodName; ReflectionProvider.java Document type: Java Project: Terasology Author: Immortius Date: Jan 23, 2014 08:35 AM 41   * @author Immortius 42   */ 43  public class ReflectionProvider<T> implements PropertyProvider<T> { 44   private static final Logger logger = LoggerFactory.getLogger(ReflectionProvider.class); 46   private List<Property<T>> properties = Lists.newArrayList(); ReflectionReflectFactory.java Document type: Java Project: Terasology Author: Immortius Date: Jan 23, 2014 08:35 AM 30   * @author Immortius 31   */ 32  public class ReflectionReflectFactory implements ReflectFactory { Content Source Code and Documents Check­in Comments Projects (56)  DataNucleus (670)  SVN_SCMI_CLI_ performance (670)  IntelliJ IDEA Community Edition (610)  Apache­Hive (439)  Kotlin (294) Show more Document Types (19)  Java (5010)  Plain (1025)  XML (472)  Html (118)  JavaScript (108) Show more APIs actually you need: Class.forname(), getDeclaredMethods(), getReturnType(), java.lang.reflect.Method An experts may know it is “reflection”. "How do I invoke a Java method when given the method name as a string?" 13
  21. 21. Java Clear All Filters Documents: MessageListenerAdapter.java Document type: Java Project: Spring Framework Author: Juergen Hoeller Date: Jul 09, 2014 292   * @see #buildListenerArguments 293   */ 294   protected Object invokeListenerMethod(String methodName, Object[] JMSException { 295   try { 296   MethodInvoker methodInvoker = new MethodInvoker(); MultiActionController.java Document type: Java Project: Spring Framework Author: Phillip Webb Date: Nov 22, 2013 0 214   * <p>Allows parameterization of handler method mappings. 215   */ 216   public final void setMethodNameResolver(MethodNameResolver method 217   this.methodNameResolver = methodNameResolver; 218   } NotifyBuilder.java Document type: Java Project: Apache­Camel Author: Claus Ibsen Date: Apr 10, 2013 06:17  676   return doWhenAnyMatches(predicate, false); 677   } 679   private NotifyBuilder doWhenAnyMatches(final Predicate predicate, received) { 680   stack.add(new EventPredicateSupport() { 681   private final AtomicBoolean matches = new AtomicBoolean(); SpelReproTests.java Document type: Java Project: Spring Framework Author: Juergen Hoeller Date: Dec 22, 201 413   /** Should be accessing Goo.getKey because 'bar' field evaluates  414   @Test 415 public void indexingAsAPropertyAccess SPR6968 1() { Check­in Comments Projects (22)  Apache­Hive (157)  Apache­Hbase (92)  IntelliJ IDEA Community Edition (72)  Apache Solr (41)  DataNucleus (18) Show more Document Types (12)  Java (455)  Plain (966)  JavaScript (159)  Html (40)  C++ (36) Show more Authors (35)  John Pullokkaran (131)  Aleksey Pivovarov (71)  zhangduo (48)  andy_jefferson (36)  Michael McCandless (33) Report java reflection Advanced Search Browse Projects Java About 5010 search results for [java reflection] Clear All Filters Documents: 45   throw new UnsupportedOperationException(); ReflectionJoinpoint.java Document type: Java Project: WildFly Author: Ales Justin Date: Jul 25, 2011 09:52 PM 30   * @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a> 31   */ 32  public class ReflectionJoinpoint extends TargetJoinpoint { 33   private final BeanInfo beanInfo; 34   private final String methodName; ReflectionProvider.java Document type: Java Project: Terasology Author: Immortius Date: Jan 23, 2014 08:35 AM 41   * @author Immortius 42   */ 43  public class ReflectionProvider<T> implements PropertyProvider<T> { 44   private static final Logger logger = LoggerFactory.getLogger(ReflectionProvider.class); 46   private List<Property<T>> properties = Lists.newArrayList(); ReflectionReflectFactory.java Document type: Java Project: Terasology Author: Immortius Date: Jan 23, 2014 08:35 AM 30   * @author Immortius 31   */ 32  public class ReflectionReflectFactory implements ReflectFactory { Content Source Code and Documents Check­in Comments Projects (56)  DataNucleus (670)  SVN_SCMI_CLI_ performance (670)  IntelliJ IDEA Community Edition (610)  Apache­Hive (439)  Kotlin (294) Show more Document Types (19)  Java (5010)  Plain (1025)  XML (472)  Html (118)  JavaScript (108) Show more APIs actually you need: Class.forname(), getDeclaredMethods(), getReturnType(), java.lang.reflect.Method | Reference | SupporReports   forname getDeclaredMethods getReturnType Method Advanced Search Browse Projects Download Results Java About 114 search results for [forname getDeclaredMethods getReturnType Method] Clear All Filters Documents: 1366   */ 1367   public static Method[] getDeclaredMethods(Class clazz) { 1368   Method[] methods = clazz.getMethods(); 1369   ArrayList list=new ArrayList(); BeanUtils.java Document type: Java Project: Spring Framework Author: Juergen Hoeller Date: Dec 22, 2014 05:46 PM Clones 250   public static Method findDeclaredMethodWithMinimalParameters(Class<?> clazz, String methodName) 251   throws IllegalArgumentException { 253   Method targetMethod = findMethodWithMinimalParameters(clazz.getDeclaredMethods(), methodName); 254   if (targetMethod == null && clazz.getSuperclass() != null) { 255   targetMethod = findDeclaredMethodWithMinimalParameters(clazz.getSuperclass(), methodName); HamletGen.java Document type: Java Project: Apache­Hadoop Common Author: Vinod Kumar Vavilapalli Date: Jun 17, 2013 03:32 AM Content Source Code and Documents Check­in Comments Projects (7)  DataNucleus (54)  SVN_SCMI_CLI_ performance (54)  Spring Framework (2)  Apache­Camel (1)  Apache­Hadoop Common (1) Show more Document Types (2)  Java (114) An experts may know it is “reflection”. "How do I invoke a Java method when given the method name as a string?" 14
  22. 22. "How do I invoke a Java method when given the method name as a string?" An experts may know it is “reflection”. Java Clear All Filters Documents: MessageListenerAdapter.java Document type: Java Project: Spring Framework Author: Juergen Hoeller Date: Jul 09, 2014 292   * @see #buildListenerArguments 293   */ 294   protected Object invokeListenerMethod(String methodName, Object[] JMSException { 295   try { 296   MethodInvoker methodInvoker = new MethodInvoker(); MultiActionController.java Document type: Java Project: Spring Framework Author: Phillip Webb Date: Nov 22, 2013 0 214   * <p>Allows parameterization of handler method mappings. 215   */ 216   public final void setMethodNameResolver(MethodNameResolver method 217   this.methodNameResolver = methodNameResolver; 218   } NotifyBuilder.java Document type: Java Project: Apache­Camel Author: Claus Ibsen Date: Apr 10, 2013 06:17  676   return doWhenAnyMatches(predicate, false); 677   } 679   private NotifyBuilder doWhenAnyMatches(final Predicate predicate, received) { 680   stack.add(new EventPredicateSupport() { 681   private final AtomicBoolean matches = new AtomicBoolean(); SpelReproTests.java Document type: Java Project: Spring Framework Author: Juergen Hoeller Date: Dec 22, 201 413   /** Should be accessing Goo.getKey because 'bar' field evaluates  414   @Test 415 public void indexingAsAPropertyAccess SPR6968 1() { Check­in Comments Projects (22)  Apache­Hive (157)  Apache­Hbase (92)  IntelliJ IDEA Community Edition (72)  Apache Solr (41)  DataNucleus (18) Show more Document Types (12)  Java (455)  Plain (966)  JavaScript (159)  Html (40)  C++ (36) Show more Authors (35)  John Pullokkaran (131)  Aleksey Pivovarov (71)  zhangduo (48)  andy_jefferson (36)  Michael McCandless (33) Report java reflection Advanced Search Browse Projects Java About 5010 search results for [java reflection] Clear All Filters Documents: 45   throw new UnsupportedOperationException(); ReflectionJoinpoint.java Document type: Java Project: WildFly Author: Ales Justin Date: Jul 25, 2011 09:52 PM 30   * @author <a href="mailto:ales.justin@jboss.org">Ales Justin</a> 31   */ 32  public class ReflectionJoinpoint extends TargetJoinpoint { 33   private final BeanInfo beanInfo; 34   private final String methodName; ReflectionProvider.java Document type: Java Project: Terasology Author: Immortius Date: Jan 23, 2014 08:35 AM 41   * @author Immortius 42   */ 43  public class ReflectionProvider<T> implements PropertyProvider<T> { 44   private static final Logger logger = LoggerFactory.getLogger(ReflectionProvider.class); 46   private List<Property<T>> properties = Lists.newArrayList(); ReflectionReflectFactory.java Document type: Java Project: Terasology Author: Immortius Date: Jan 23, 2014 08:35 AM 30   * @author Immortius 31   */ 32  public class ReflectionReflectFactory implements ReflectFactory { Content Source Code and Documents Check­in Comments Projects (56)  DataNucleus (670)  SVN_SCMI_CLI_ performance (670)  IntelliJ IDEA Community Edition (610)  Apache­Hive (439)  Kotlin (294) Show more Document Types (19)  Java (5010)  Plain (1025)  XML (472)  Html (118)  JavaScript (108) Show more APIs actually you need: Class.forname(), getDeclaredMethods(), getReturnType(), java.lang.reflect.Method | Reference | SupporReports   forname getDeclaredMethods getReturnType Method Advanced Search Browse Projects Download Results Java About 114 search results for [forname getDeclaredMethods getReturnType Method] Clear All Filters Documents: 1366   */ 1367   public static Method[] getDeclaredMethods(Class clazz) { 1368   Method[] methods = clazz.getMethods(); 1369   ArrayList list=new ArrayList(); BeanUtils.java Document type: Java Project: Spring Framework Author: Juergen Hoeller Date: Dec 22, 2014 05:46 PM Clones 250   public static Method findDeclaredMethodWithMinimalParameters(Class<?> clazz, String methodName) 251   throws IllegalArgumentException { 253   Method targetMethod = findMethodWithMinimalParameters(clazz.getDeclaredMethods(), methodName); 254   if (targetMethod == null && clazz.getSuperclass() != null) { 255   targetMethod = findDeclaredMethodWithMinimalParameters(clazz.getSuperclass(), methodName); HamletGen.java Document type: Java Project: Apache­Hadoop Common Author: Vinod Kumar Vavilapalli Date: Jun 17, 2013 03:32 AM Content Source Code and Documents Check­in Comments Projects (7)  DataNucleus (54)  SVN_SCMI_CLI_ performance (54)  Spring Framework (2)  Apache­Camel (1)  Apache­Hadoop Common (1) Show more Document Types (2)  Java (114) Vocabulary Mismatch Problem 15
  23. 23. Yes, we can ask: 16
  24. 24. “This is a snippet for you.” How should they look like? What if you need real code examples? 17
  25. 25. Intuition 18
  26. 26. Insight from SMT [From English to Korean] When a translator does not work well… 19
  27. 27. Insight from SMT [From English to Korean] When a translator does not work well… 19
  28. 28. Insight from SMT [From English to Korean] When a translator does not work well… 19
  29. 29. Insight from SMT [From English to Korean] When a translator does not work well… 19
  30. 30. Insight from SMT When a translator does not work well… [From English to Korean] 20
  31. 31. Insight from SMT When a translator does not work well… 20
  32. 32. Insight from SMT Taking two steps! 21
  33. 33. Insight from SMT Taking two steps! English —> Japanese 21
  34. 34. Insight from SMT Taking two steps! English —> Japanese —> Korean 21
  35. 35. Augmenting queries Query 22
  36. 36. Augmenting queries Query invoke Java method name string 22
  37. 37. Augmenting queries Query invoke Java method name string 22
  38. 38. Augmenting queries Query invoke Java method name string Mappings between questions and snippets 22
  39. 39. Augmenting queries Query invoke Java method name string Mappings between questions and snippets 22
  40. 40. Augmenting queries Query Augmented query invoke Java method name string Mappings between questions and snippets 22
  41. 41. Augmenting queries Query Augmented query invoke Java method name string Mappings between questions and snippets 22
  42. 42. Augmenting queries Query Augmented query java.lang.reflect.Method Class.forName() getDeclaredMethods() getReturnType() invoke Java method name string Mappings between questions and snippets 22
  43. 43. Augmenting queries Query invoke, Java, method, name, string Augmented query java.lang.reflect.Method Class.forName() getDeclaredMethods() getReturnType() invoke Java method name string Mappings between questions and snippets 22
  44. 44. ApproachCoCaBu:Code voCaBulary 23
  45. 45. Search Query Search Proxy Relevant Posts Code Query Generator Snippet Index Augmented Query Code Index Code Search Engine (a) (b) (c) Search Results Overview 24
  46. 46. Generating random words in Java? <<Query>> (1) Searching for Similar Questions (+ Snippets) 25
  47. 47. Generating random words in Java? <<Query>> How to create random string with random characters? Random string generation Random word from array list How to Generate Words Randomly in JavaGenerating random words of a certain length in java? (1) Searching for Similar Questions (+ Snippets) 25
  48. 48. Generating random words in Java? <<Query>> String Functions Generics Collections & Util Package Nested Classes Networking File I/O Operations Java Annotations JDBC Examples Spring Core Java Interview Questions Java Interview Programs Java Restful Web Services JSON in Java JUnit Java Design Patterns Search Algorithms Sorting Algorithms Data Structures Gradle Configurations JBoss Configurations Java Issues Output: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 package com.java2novice.random;   import java.util.Random;   public class MyStringRandomGen {       private static final String CHAR_LIST =          "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";     private static final int RANDOM_STRING_LENGTH = 10;           /**      * This method generates random string      * @return      */     public String generateRandomString(){                   StringBuffer randStr = new StringBuffer();         for(int i=0; i<RANDOM_STRING_LENGTH; i++){             int number = getRandomNumber();             char ch = CHAR_LIST.charAt(number);             randStr.append(ch);         }         return randStr.toString();     }           /**      * This method generates random numbers      * @return int      */     private int getRandomNumber() {         int randomInt = 0;         Random randomGenerator = new Random();         randomInt = randomGenerator.nextInt(CHAR_LIST.length());         if (randomInt ‐ 1 == ‐1) {             return randomInt;         } else {             return randomInt ‐ 1;         }     }           public static void main(String a[]){         MyStringRandomGen msr = new MyStringRandomGen();         System.out.println(msr.generateRandomString());         System.out.println(msr.generateRandomString());         System.out.println(msr.generateRandomString());         System.out.println(msr.generateRandomString());         System.out.println(msr.generateRandomString());         System.out.println(msr.generateRandomString());         System.out.println(msr.generateRandomString());     } } Be the first of your friends to like this Java Sample Programs 7,256 likes Like Page How to create random string with random characters? Random string generation posted 10/13/2004 1:55 AM  posted 10/13/2004 2:15 AM posted 10/13/2004 2:17 AM  posted 10/13/2004 5:45 AM  Anna Hays  Ranch Hand  Joined: Nov 09, 2003 Posts: 131  Hi, can Java generate a string of random charactors? I need a password generation. Can so me an idea of what's the proper way of doing this please? Thanks. Michael Dunn  Ranch Hand  Joined: Jun 09, 2003 Posts: 4632  This might be one way Steve Deadsea  Ranch Hand  Joined: Dec 03, 2001 Posts: 125  I wrote libraries for doing this: http://ostermiller.org/utils/RandPass.html somkiat puisungnoen  Ranch Hand  Joined: Jul 04, 2003 Posts: 1312  Originally posted by Anna Kafei: Hi, can Java generate a string of random charactors? I need a password generation. Can som me an idea of what's the proper way of doing this please? Thanks. 1. Specified your data for random. 2. Specified length for generate password. 3. Create random utilities , you can use Math.random() method or java.util.Random class. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 class Testing {   public Testing()   {     final int PASSWORD_LENGTH = 8;     StringBuffer sb = new StringBuffer();     for (int x = 0; x < PASSWORD_LENGTH; x++)     {       sb.append((char)((int)(Math.random()*26)+97));     }     System.out.println(sb.toString());   }   public static void main(String[] args){new Testing();} }   //Construct String from file   public static void constructor(String filename) throws IOException{   ArrayList words = new ArrayList();   BufferedReader read = new BufferedReader(new FileReader("filename"));   String line = read.readLine();     while (line != null){       words.add(line);       //line = reader.readline();     }   }   public static void getRandomWord(){ Random rand = new Random(); String randomWord = words.get(rand.nextInt(words.size)); } } java random arraylist asked Dec 3 '13 at 18:35 user3062703 1 1 1     – So you're trying to get a random word from a file and output it? Tatakai Wasumi Dec 3 '13 at 18:49     –  Member variables (e.g. 'words') cannot be referenced from static methods (e.g. 'getRandomWord()'). declare 'words' as static or remove 'static' keyword from method signature. Hollis Waite Dec 3 '13 18:49     – you should use something like : int rand= minimum + (int)(Math.random()*maximum); Clad Clad De at 18:50     – Try this link maybe it will help you here Tatakai Wasumi Dec 3 '13 at 18:52     –  @TatakaiWasumi Indeed. From what I understand the first part of my code takes words from a file an them in an arraylist. The second part of my code needs to generate a random number and from that, the corresponding word in the arraylist. I'm having issues with the fact that words is private... Says I reach it from getRandomWord user3062703 Dec 3 '13 at 18:57 1 Answer This will help you I think It's able to get a random word from an array of strings private static String[] names = { "Terminator", "Slicer","Ninja", "cow", "Robot",  "littlegirl" }; name = names[(int) (Math.random() * names.length)]; System.out.println(names); Random word from array list How to Generate Words Randomly in Java How to Add Buttons and Text to Your JavaFX Project Making You Easier with How to Generate Words Rando By Barry Burd from Beginning Programming with Java Fo Most Java programs don’t work correctly the first time you run error on your part. This code is a case in point. To write this code, you need a way to generate three­letter wo anAccount.lastName = "" + (char) (myRandom.nextInt(26) + 'A') + (char) (myRandom.nextInt(26) + 'a') + (char) (myRandom.nextInt(26) + 'a'); Here’s how the code works: Each call to the Random.nextInt(26)generates a num Adding'A'gives you a number from 65 to 90. To store a letter 'A', the computer puts the number 65 in adding 'A' to 25 gives you 90. Applying(char)to a number turns the number into a cha To store the letters 'A' through 'Z', the computer puts th   speaks 9 Promoted by Babbel Promoted by Lifestyle Journal   Generating random words of a certain length in java? Do you need actual English words, or just random strings that only contain letters a­z? If you need actual English words, the only way to do it is to use a dictionary, and select words from it at random. If you don't need English words, then something like this will do: share edit flag edited Feb 10 '11 at 1:01 David Yaw 22k 2 45 81 answered Feb 10 '11 at 0:17 public static String[] generateRandomWords(int numberOfWords) { String[] randomStrings = new String[numberOfWords]; Random random = new Random(); for(int i = 0; i < numberOfWords; i++) { char[] word = new char[random.nextInt(8)+3]; // words of length 3 through 10. for(int j = 0; j < word.length; j++) { word[j] = (char)('a' + random.nextInt(26)); } randomStrings[i] = new String(word); } return randomStrings; } (1) Searching for Similar Questions (+ Snippets) 25
  49. 49. (2) Generating Augmented Queries 26
  50. 50. Generating random words in Java? <<Query>> (2) Generating Augmented Queries 26
  51. 51. Generating random words in Java? <<Query>> (2) Generating Augmented Queries 26
  52. 52. Generating random words of a certain length in java? Do you need actual English words, or just random strings that only contain letters a­z? If you need actual English words, the only way to do it is to use a dictionary, and select words from it at random. If you don't need English words, then something like this will do: public static String[] generateRandomWords(int numberOfWords) { String[] randomStrings = new String[numberOfWords]; Random random = new Random(); for(int i = 0; i < numberOfWords; i++) { char[] word = new char[random.nextInt(8)+3]; // words of length 3 through 10. for(int j = 0; j < word.length; j++) { word[j] = (char)('a' + random.nextInt(26)); } randomStrings[i] = new String(word); } return randomStrings; } Generating random words in Java? <<Query>> (2) Generating Augmented Queries 26
  53. 53. Generating random words of a certain length in java? Do you need actual English words, or just random strings that only contain letters a­z? If you need actual English words, the only way to do it is to use a dictionary, and select words from it at random. If you don't need English words, then something like this will do: public static String[] generateRandomWords(int numberOfWords) { String[] randomStrings = new String[numberOfWords]; Random random = new Random(); for(int i = 0; i < numberOfWords; i++) { char[] word = new char[random.nextInt(8)+3]; // words of length 3 through 10. for(int j = 0; j < word.length; j++) { word[j] = (char)('a' + random.nextInt(26)); } randomStrings[i] = new String(word); } return randomStrings; } Generating random words in Java? <<Query>> (2) Generating Augmented Queries 26
  54. 54. 3.3 Code Query Generator The Code Query Generator creates a code search query that augments the free-form query taken by the search proxy (Section 3.2). This augmented query is a list of program ele- ments, such as class and method names (e.g., Math.random), as well as natural language terms which can be used to match documentation. To generate the augmented query, CoCaBu must extract structural code entities from code snippets embedded in the answers to the questions in the relevant posts returned by the search proxy (Figure 6(b)). The code query generator component only considers accepted answers, i.e., answers approved by the Q&A site community. The augmented query produced by the code query gener- 3.3 Code Query Generator The Code Query Generator creates a code search query that augments the free-form query taken by the search proxy (Section 3.2). This augmented query is a list of program ele- ments, such as class and method names (e.g., Math.random), as well as natural language terms which can be used to match documentation. To generate the augmented query, CoCaBu must extract structural code entities from code snippets embedded in the answers to the questions in the relevant posts returned by the search proxy (Figure 6(b)). The code query generator component only considers accepted answers, i.e., answers approved by the Q&A site community. The augmented query produced by the code query gener- ator is illustrated in Figure 6 in the Lucene search engine query format. Generating random words in Java? How to create random string with random c JAVA EXAMPLE PROGRAMS Home Fundamentals Constructors Exception Handling Threads String Functions Generics Collections & Util Package Nested Classes Networking File I/O Operations Java Annotations JDBC Examples Spring Core Java Interview Questions Program: How to create random string with rand Description: Write a program to generate random string of length 10 charactors. E program should generate random string. Code: Monitor Jav 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 package com.java2novice.random;   import java.util.Random;   public class MyStringRandomGen {       private static final String CHAR_LIST =          "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQ     private static final int RANDOM_STRING_LENGTH =            /**      * This method generates random string      * @return      */     public String generateRandomString(){                   StringBuffer randStr = new StringBuffer();         for(int i=0; i<RANDOM_STRING_LENGTH; i++){             int number = getRandomNumber();             char ch = CHAR_LIST.charAt(number);             randStr.append(ch);         }         return randStr.toString();     } Random string generation posted 10/13/2004 1:55 AM  posted 10/13/2004 2:15 AM A friendly place for programming greenhorns! Bi   Search | Java FAQ | Recen Win a copy of Introducing JavaRanch » Java Forums » Java » Java in General   Author Random string generatio Anna Hays  Ranch Hand  Joined: Nov 09, 2003 Posts: 131  Hi, can Java generate a string of random charactors? I n me an idea of what's the proper way of doing this please Michael Dunn  Ranch Hand  Joined: Jun 09, 2003 Posts: 4632  This might be one way 1 2 3 4 5 6 7 class Testing {   public Testing()   {     final int PASSWORD_LENGTH = 8;     StringBuffer sb = new StringBuffer();     for (int x = 0; x < PASSWORD_LENGTH; How to Genera How to Add Butt Text to Your Jav Project How to Gen By Barry Burd from B Most Java programs do error on your part. This  To write this code, you    10 easy tricks to learn any language from a man who speaks 9 Promoted by Babbel     private ArrayList   //Construct Strin   public static voi   ArrayList words =   BufferedReader re   String line = rea     while (line !=        words.add(lin       //line = read     }   }   public static voi Random rand = new R String randomWord = } } java random arra asked Dec 3 '13 at 18 user3062703 1 1 1     So you're trying to g     Member variables (e declare 'words' as s 18:49     you should use som at 18:50     Try this link maybe     @TatakaiWasumi In them in an arraylist. the corresponding w reach it from getRa 2 <<Query>> <<Relevent-Posts>> 2 Answers(a) example query whose field semantics was pre in Table 1: • terms, excluding stop words, in the use (cf. Figure 6(a)) are kept, after stemm mented query (cf. Figure 6(c), lines • structural code entities collected from (cf. Figure 6(b)) are mentioned with non-qualified/partially qualified metho class) in the augmented query (cf. Figu IxJ) To accelerate code query generation, Co an index of posts. Typically, Q&A forums of their posts. These posts are often forma tural language such as XML. For example, flow posts, code snippets are enclosed in <co As shown in Figure 8, our approach takes posts from a Q&A site and extracts metadat tion title) and code snippets for each post. pet is then analyzed to retrieve the structur This phase presents challenges that will be a tion 3.1. Metadata pq_method_invocation:Random.nextInt pq_method_invocation:Math.random class:word class:char class:int class:String class:Random instance:String instance:Random nq_method_invocation:nextInt code:gener code:random code:word ... Figure 7: Augmented query corresponding to the sn in Figure ??. Generating random words of a certain length in java? Do you need actual English words, or just random strings that only contain letters a­z? If you need actual English words, the only way to do it is to use a dictionary, and select words from it at random. If you don't need English words, then something like this will do: public static String[] generateRandomWords(int numberOfWords) { String[] randomStrings = new String[numberOfWords]; Random random = new Random(); for(int i = 0; i < numberOfWords; i++) { char[] word = new char[random.nextInt(8)+3]; // words of length 3 through 10. for(int j = 0; j < word.length; j++) { word[j] = (char)('a' + random.nextInt(26)); } randomStrings[i] = new String(word); } return randomStrings; } Generating random words in Java? <<Query>> (2) Generating Augmented Queries 26
  55. 55. 3.3 Code Query Generator The Code Query Generator creates a code search query that augments the free-form query taken by the search proxy (Section 3.2). This augmented query is a list of program ele- ments, such as class and method names (e.g., Math.random), as well as natural language terms which can be used to match documentation. To generate the augmented query, CoCaBu must extract structural code entities from code snippets embedded in the answers to the questions in the relevant posts returned by the search proxy (Figure 6(b)). The code query generator component only considers accepted answers, i.e., answers approved by the Q&A site community. The augmented query produced by the code query gener- 3.3 Code Query Generator The Code Query Generator creates a code search query that augments the free-form query taken by the search proxy (Section 3.2). This augmented query is a list of program ele- ments, such as class and method names (e.g., Math.random), as well as natural language terms which can be used to match documentation. To generate the augmented query, CoCaBu must extract structural code entities from code snippets embedded in the answers to the questions in the relevant posts returned by the search proxy (Figure 6(b)). The code query generator component only considers accepted answers, i.e., answers approved by the Q&A site community. The augmented query produced by the code query gener- ator is illustrated in Figure 6 in the Lucene search engine query format. Generating random words in Java? How to create random string with random c JAVA EXAMPLE PROGRAMS Home Fundamentals Constructors Exception Handling Threads String Functions Generics Collections & Util Package Nested Classes Networking File I/O Operations Java Annotations JDBC Examples Spring Core Java Interview Questions Program: How to create random string with rand Description: Write a program to generate random string of length 10 charactors. E program should generate random string. Code: Monitor Jav 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 package com.java2novice.random;   import java.util.Random;   public class MyStringRandomGen {       private static final String CHAR_LIST =          "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQ     private static final int RANDOM_STRING_LENGTH =            /**      * This method generates random string      * @return      */     public String generateRandomString(){                   StringBuffer randStr = new StringBuffer();         for(int i=0; i<RANDOM_STRING_LENGTH; i++){             int number = getRandomNumber();             char ch = CHAR_LIST.charAt(number);             randStr.append(ch);         }         return randStr.toString();     } Random string generation posted 10/13/2004 1:55 AM  posted 10/13/2004 2:15 AM A friendly place for programming greenhorns! Bi   Search | Java FAQ | Recen Win a copy of Introducing JavaRanch » Java Forums » Java » Java in General   Author Random string generatio Anna Hays  Ranch Hand  Joined: Nov 09, 2003 Posts: 131  Hi, can Java generate a string of random charactors? I n me an idea of what's the proper way of doing this please Michael Dunn  Ranch Hand  Joined: Jun 09, 2003 Posts: 4632  This might be one way 1 2 3 4 5 6 7 class Testing {   public Testing()   {     final int PASSWORD_LENGTH = 8;     StringBuffer sb = new StringBuffer();     for (int x = 0; x < PASSWORD_LENGTH; How to Genera How to Add Butt Text to Your Jav Project How to Gen By Barry Burd from B Most Java programs do error on your part. This  To write this code, you    10 easy tricks to learn any language from a man who speaks 9 Promoted by Babbel     private ArrayList   //Construct Strin   public static voi   ArrayList words =   BufferedReader re   String line = rea     while (line !=        words.add(lin       //line = read     }   }   public static voi Random rand = new R String randomWord = } } java random arra asked Dec 3 '13 at 18 user3062703 1 1 1     So you're trying to g     Member variables (e declare 'words' as s 18:49     you should use som at 18:50     Try this link maybe     @TatakaiWasumi In them in an arraylist. the corresponding w reach it from getRa 2 <<Query>> <<Relevent-Posts>> 2 Answers(a) example query whose field semantics was pre in Table 1: • terms, excluding stop words, in the use (cf. Figure 6(a)) are kept, after stemm mented query (cf. Figure 6(c), lines • structural code entities collected from (cf. Figure 6(b)) are mentioned with non-qualified/partially qualified metho class) in the augmented query (cf. Figu IxJ) To accelerate code query generation, Co an index of posts. Typically, Q&A forums of their posts. These posts are often forma tural language such as XML. For example, flow posts, code snippets are enclosed in <co As shown in Figure 8, our approach takes posts from a Q&A site and extracts metadat tion title) and code snippets for each post. pet is then analyzed to retrieve the structur This phase presents challenges that will be a tion 3.1. Metadata pq_method_invocation:Random.nextInt pq_method_invocation:Math.random class:word class:char class:int class:String class:Random instance:String instance:Random nq_method_invocation:nextInt code:gener code:random code:word ... Figure 7: Augmented query corresponding to the sn in Figure ??. Generating random words of a certain length in java? Do you need actual English words, or just random strings that only contain letters a­z? If you need actual English words, the only way to do it is to use a dictionary, and select words from it at random. If you don't need English words, then something like this will do: public static String[] generateRandomWords(int numberOfWords) { String[] randomStrings = new String[numberOfWords]; Random random = new Random(); for(int i = 0; i < numberOfWords; i++) { char[] word = new char[random.nextInt(8)+3]; // words of length 3 through 10. for(int j = 0; j < word.length; j++) { word[j] = (char)('a' + random.nextInt(26)); } randomStrings[i] = new String(word); } return randomStrings; } Generating random words in Java? <<Query>> 27
  56. 56. 3.3 Code Query Generator The Code Query Generator creates a code search query that augments the free-form query taken by the search proxy (Section 3.2). This augmented query is a list of program ele- ments, such as class and method names (e.g., Math.random), as well as natural language terms which can be used to match documentation. To generate the augmented query, CoCaBu must extract structural code entities from code snippets embedded in the answers to the questions in the relevant posts returned by the search proxy (Figure 6(b)). The code query generator component only considers accepted answers, i.e., answers approved by the Q&A site community. The augmented query produced by the code query gener- 3.3 Code Query Generator The Code Query Generator creates a code search query that augments the free-form query taken by the search proxy (Section 3.2). This augmented query is a list of program ele- ments, such as class and method names (e.g., Math.random), as well as natural language terms which can be used to match documentation. To generate the augmented query, CoCaBu must extract structural code entities from code snippets embedded in the answers to the questions in the relevant posts returned by the search proxy (Figure 6(b)). The code query generator component only considers accepted answers, i.e., answers approved by the Q&A site community. The augmented query produced by the code query gener- ator is illustrated in Figure 6 in the Lucene search engine query format. Generating random words in Java? How to create random string with random c JAVA EXAMPLE PROGRAMS Home Fundamentals Constructors Exception Handling Threads String Functions Generics Collections & Util Package Nested Classes Networking File I/O Operations Java Annotations JDBC Examples Spring Core Java Interview Questions Program: How to create random string with rand Description: Write a program to generate random string of length 10 charactors. E program should generate random string. Code: Monitor Jav 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 package com.java2novice.random;   import java.util.Random;   public class MyStringRandomGen {       private static final String CHAR_LIST =          "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQ     private static final int RANDOM_STRING_LENGTH =            /**      * This method generates random string      * @return      */     public String generateRandomString(){                   StringBuffer randStr = new StringBuffer();         for(int i=0; i<RANDOM_STRING_LENGTH; i++){             int number = getRandomNumber();             char ch = CHAR_LIST.charAt(number);             randStr.append(ch);         }         return randStr.toString();     } Random string generation posted 10/13/2004 1:55 AM  posted 10/13/2004 2:15 AM A friendly place for programming greenhorns! Bi   Search | Java FAQ | Recen Win a copy of Introducing JavaRanch » Java Forums » Java » Java in General   Author Random string generatio Anna Hays  Ranch Hand  Joined: Nov 09, 2003 Posts: 131  Hi, can Java generate a string of random charactors? I n me an idea of what's the proper way of doing this please Michael Dunn  Ranch Hand  Joined: Jun 09, 2003 Posts: 4632  This might be one way 1 2 3 4 5 6 7 class Testing {   public Testing()   {     final int PASSWORD_LENGTH = 8;     StringBuffer sb = new StringBuffer();     for (int x = 0; x < PASSWORD_LENGTH; How to Genera How to Add Butt Text to Your Jav Project How to Gen By Barry Burd from B Most Java programs do error on your part. This  To write this code, you    10 easy tricks to learn any language from a man who speaks 9 Promoted by Babbel     private ArrayList   //Construct Strin   public static voi   ArrayList words =   BufferedReader re   String line = rea     while (line !=        words.add(lin       //line = read     }   }   public static voi Random rand = new R String randomWord = } } java random arra asked Dec 3 '13 at 18 user3062703 1 1 1     So you're trying to g     Member variables (e declare 'words' as s 18:49     you should use som at 18:50     Try this link maybe     @TatakaiWasumi In them in an arraylist. the corresponding w reach it from getRa 2 <<Query>> <<Relevent-Posts>> 2 Answers(a) example query whose field semantics was pre in Table 1: • terms, excluding stop words, in the use (cf. Figure 6(a)) are kept, after stemm mented query (cf. Figure 6(c), lines • structural code entities collected from (cf. Figure 6(b)) are mentioned with non-qualified/partially qualified metho class) in the augmented query (cf. Figu IxJ) To accelerate code query generation, Co an index of posts. Typically, Q&A forums of their posts. These posts are often forma tural language such as XML. For example, flow posts, code snippets are enclosed in <co As shown in Figure 8, our approach takes posts from a Q&A site and extracts metadat tion title) and code snippets for each post. pet is then analyzed to retrieve the structur This phase presents challenges that will be a tion 3.1. Metadata pq_method_invocation:Random.nextInt pq_method_invocation:Math.random class:word class:char class:int class:String class:Random instance:String instance:Random nq_method_invocation:nextInt code:gener code:random code:word ... Figure 7: Augmented query corresponding to the sn in Figure ??. 27
  57. 57. 3.3 Code Query Generator The Code Query Generator creates a code search query that augments the free-form query taken by the search proxy (Section 3.2). This augmented query is a list of program ele- ments, such as class and method names (e.g., Math.random), as well as natural language terms which can be used to match documentation. To generate the augmented query, CoCaBu must extract structural code entities from code snippets embedded in the answers to the questions in the relevant posts returned by the search proxy (Figure 6(b)). The code query generator component only considers accepted answers, i.e., answers approved by the Q&A site community. The augmented query produced by the code query gener- 3.3 Code Query Generator The Code Query Generator creates a code search query that augments the free-form query taken by the search proxy (Section 3.2). This augmented query is a list of program ele- ments, such as class and method names (e.g., Math.random), as well as natural language terms which can be used to match documentation. To generate the augmented query, CoCaBu must extract structural code entities from code snippets embedded in the answers to the questions in the relevant posts returned by the search proxy (Figure 6(b)). The code query generator component only considers accepted answers, i.e., answers approved by the Q&A site community. The augmented query produced by the code query gener- ator is illustrated in Figure 6 in the Lucene search engine query format. Generating random words in Java? How to create random string with random c JAVA EXAMPLE PROGRAMS Home Fundamentals Constructors Exception Handling Threads String Functions Generics Collections & Util Package Nested Classes Networking File I/O Operations Java Annotations JDBC Examples Spring Core Java Interview Questions Program: How to create random string with rand Description: Write a program to generate random string of length 10 charactors. E program should generate random string. Code: Monitor Jav 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 package com.java2novice.random;   import java.util.Random;   public class MyStringRandomGen {       private static final String CHAR_LIST =          "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQ     private static final int RANDOM_STRING_LENGTH =            /**      * This method generates random string      * @return      */     public String generateRandomString(){                   StringBuffer randStr = new StringBuffer();         for(int i=0; i<RANDOM_STRING_LENGTH; i++){             int number = getRandomNumber();             char ch = CHAR_LIST.charAt(number);             randStr.append(ch);         }         return randStr.toString();     } Random string generation posted 10/13/2004 1:55 AM  posted 10/13/2004 2:15 AM A friendly place for programming greenhorns! Bi   Search | Java FAQ | Recen Win a copy of Introducing JavaRanch » Java Forums » Java » Java in General   Author Random string generatio Anna Hays  Ranch Hand  Joined: Nov 09, 2003 Posts: 131  Hi, can Java generate a string of random charactors? I n me an idea of what's the proper way of doing this please Michael Dunn  Ranch Hand  Joined: Jun 09, 2003 Posts: 4632  This might be one way 1 2 3 4 5 6 7 class Testing {   public Testing()   {     final int PASSWORD_LENGTH = 8;     StringBuffer sb = new StringBuffer();     for (int x = 0; x < PASSWORD_LENGTH; How to Genera How to Add Butt Text to Your Jav Project How to Gen By Barry Burd from B Most Java programs do error on your part. This  To write this code, you    10 easy tricks to learn any language from a man who speaks 9 Promoted by Babbel     private ArrayList   //Construct Strin   public static voi   ArrayList words =   BufferedReader re   String line = rea     while (line !=        words.add(lin       //line = read     }   }   public static voi Random rand = new R String randomWord = } } java random arra asked Dec 3 '13 at 18 user3062703 1 1 1     So you're trying to g     Member variables (e declare 'words' as s 18:49     you should use som at 18:50     Try this link maybe     @TatakaiWasumi In them in an arraylist. the corresponding w reach it from getRa 2 <<Query>> <<Relevent-Posts>> 2 Answers(a) example query whose field semantics was pre in Table 1: • terms, excluding stop words, in the use (cf. Figure 6(a)) are kept, after stemm mented query (cf. Figure 6(c), lines • structural code entities collected from (cf. Figure 6(b)) are mentioned with non-qualified/partially qualified metho class) in the augmented query (cf. Figu IxJ) To accelerate code query generation, Co an index of posts. Typically, Q&A forums of their posts. These posts are often forma tural language such as XML. For example, flow posts, code snippets are enclosed in <co As shown in Figure 8, our approach takes posts from a Q&A site and extracts metadat tion title) and code snippets for each post. pet is then analyzed to retrieve the structur This phase presents challenges that will be a tion 3.1. Metadata pq_method_invocation:Random.nextInt pq_method_invocation:Math.random class:word class:char class:int class:String class:Random instance:String instance:Random nq_method_invocation:nextInt code:gener code:random code:word ... Figure 7: Augmented query corresponding to the sn in Figure ??. 28
  58. 58. y y - , h t e y r s - e arch proxy ogram ele- h.random), d to match ust extract ded in the turned by generator ., answers ery gener- rch engine How to create random string with random characters? dling ns Util Package tions ns s Questions Programs eb Services Program: How to create random string with random characters? Description: Write a program to generate random string of length 10 charactors. Every time you call the method, the program should generate random string. Code: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 package com.java2novice.random;   import java.util.Random;   public class MyStringRandomGen {       private static final String CHAR_LIST =          "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";     private static final int RANDOM_STRING_LENGTH = 10;           /**      * This method generates random string      * @return      */     public String generateRandomString(){                   StringBuffer randStr = new StringBuffer();         for(int i=0; i<RANDOM_STRING_LENGTH; i++){             int number = getRandomNumber();             char ch = CHAR_LIST.charAt(number);             randStr.append(ch);         }         return randStr.toString();     }           /**      * This method generates random numbers      * @return int      */     private int getRandomNumber() {         int randomInt = 0;         Random randomGenerator = new Random(); Be the first of your friends to like this Java Sample Programs 7,256 likes Like Page ? Random string generation posted 10/13/2004 1:55 AM  posted 10/13/2004 2:15 AM A friendly place for programming greenhorns! Big Moose Saloon   Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies  Register / Login  Win a copy of Introducing JavaFX 8 Programming this week in the JavaFX forum! JavaRanch » Java Forums » Java » Java in General   Author Random string generation Anna Hays  Ranch Hand  Joined: Nov 09, 2003 Posts: 131  Hi, can Java generate a string of random charactors? I need a password generation. Can someone give me an idea of what's the proper way of doing this please? Thanks. Michael Dunn  Ranch Hand  Joined: Jun 09, 2003 Posts: 4632  This might be one way 1 2 3 4 5 6 7 8 9 10 11 12 13 14 class Testing {   public Testing()   {     final int PASSWORD_LENGTH = 8;     StringBuffer sb = new StringBuffer();     for (int x = 0; x < PASSWORD_LENGTH; x++)     {       sb.append((char)((int)(Math.random()*26)+97));     }     System.out.println(sb.toString());   }   public static void main(String[] args){new Testing();} } ? How to Generate Words Randomly in Java How to Add Buttons and Text to Your JavaFX Project Making Your Page Layouts Easier with Includes Create a Java How to Generate Words Randomly in Java By Barry Burd from Beginning Programming with Java For Dummies, 4th Edition Most Java programs don’t work correctly the first time you run them, and some programs don’t work w error on your part. This code is a case in point. To write this code, you need a way to generate three­letter words randomly. This code would give you anAccount.lastName = "" + (char) (myRandom.nextInt(26) + 'A') + (char) (myRandom.nextInt(26) + 'a') + (char) (myRandom.nextInt(26) + 'a');   10 easy tricks to learn any language from a man who speaks 9 Promoted by Babbel Unique Method May Regrow Lost Hair Promoted by Lifestyle Journal Seven Foods That Fight Inflammation and Belly Fat ­ For Dummies The  Plan Sam Wom   Random word from array list     while (line != null){       words.add(line);       //line = reader.readline();     }   }   public static void getRandomWord(){ Random rand = new Random(); String randomWord = words.get(rand.nextInt(words.size)); } } java random arraylist asked Dec 3 '13 at 18:35 user3062703 1 1 1     – So you're trying to get a random word from a file and output it? Tatakai Wasumi Dec 3 '13 at 18:49     –  Member variables (e.g. 'words') cannot be referenced from static methods (e.g. 'getRandomWord()'). Either declare 'words' as static or remove 'static' keyword from method signature. Hollis Waite Dec 3 '13 at 18:49     – you should use something like : int rand= minimum + (int)(Math.random()*maximum); Clad Clad Dec 3 '13 at 18:50     – Try this link maybe it will help you here Tatakai Wasumi Dec 3 '13 at 18:52     –  @TatakaiWasumi Indeed. From what I understand the first part of my code takes words from a file and puts them in an arraylist. The second part of my code needs to generate a random number and from that, output the corresponding word in the arraylist. I'm having issues with the fact that words is private... Says I can't reach it from getRandomWord user3062703 Dec 3 '13 at 18:57 1 Answer This will help you I think It's able to get a random word from an array of strings private static String[] names = { "Terminator", "Slicer","Ninja", "cow", "Robot",  "littlegirl" }; Generating random words of a certain length in java? 2 Answers What kind of words do you want to generate? Random lowercase characters? String getRandomWord(int length) { want to generate? Random lowercase characters? gth) { • In case the query is augmented, granularity is further controlled since the structural code entities matched • terms, excluding stop words, in the user free-form query (cf. Figure 6(a)) are kept, after stemming, in the aug- mented query (cf. Figure 6(c), lines Bissyande IxJ) • structural code entities collected from Q&A snippets (cf. Figure 6(b)) are mentioned with their type (e.g., non-qualified/partially qualified method invocation, or class) in the augmented query (cf. Figure 6(c), lines Bissyande IxJ) To accelerate code query generation, CoCaBu builds on an index of posts. Typically, Q&A forums provide archives of their posts. These posts are often formatted by a struc- tural language such as XML. For example, in Stack Over- flow posts, code snippets are enclosed in <code> ...</code>. As shown in Figure 8, our approach takes pre-downloaded posts from a Q&A site and extracts metadata (post ID, ques- tion title) and code snippets for each post. Each code snip- pet is then analyzed to retrieve the structural code entities. This phase presents challenges that will be addressed in Sec- tion 3.1. Q&A Posts Code
 Metadata Post Analyzer Snippet Index pq_method_invocation:Random.nextInt pq_method_invocation:Math.random class:word class:char class:int class:String class:Random instance:String instance:Random nq_method_invocation:nextInt code:gener code:random code:word ... Figure 7: Augmented query corresponding to the snippet shown in Figure ??. in Table 1: • terms, excluding stop words, in the user free-form query (cf. Figure 6(a)) are kept, after stemming, in the aug- 28
  59. 59. 27 28 29 buf[i] = chars[random.nextInt(chars.length)]; } return new String(buf); Source: PasswordGenerator.java  Score: 34.5651054382 24 25 26 27 28 29 "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2", "3", "5", "6", "7", "8", "9" }; public static final Random random = new Random(); /** 36 37 38 39 40 41 String password = ""; for (int i = 0; i < PASSWORD_LENGTH; i++) { password += CHARSET[random.nextInt(CHARSET.length)]; } return password; Source: RandomString.java  Score: 34.2108421326 22 23 24 25 26 27 } private final Random random = new Random(); private final char[] buf; 36 37 38 39 40 public String nextString() { for (int idx = 0; idx < buf.length; ++idx) buf[idx] = symbols[random.nextInt(symbols.length)]; return new String(buf); } Title: Generating random words in Java?  Source: RandomString.java  Description: If you don't need English words, then something li will do:  Score: 37.1969795227 24 25 26 27 28 29 public class RandomString { private static final char[] symbols = new char[36]; private static final Random random = new Random(); static { 37 38 39 40 41 42 { char[] buf = new char[length]; for (int idx = 0; idx < length; ++idx) buf[idx] = symbols[random.nextInt(symbols.length)]; return new String(buf); } Title: Generating random words in Java?  Source: IdGenerator.java  Description: If you don't need English words, then something li will do:  Score: 36.7602005005 3 4 public class IdGenerator { Source: IdGenerator.java  Score: 36.7602005005 3 4 5 6 7 public class IdGenerator { static final Random random = new Random(); static final char[] chars = new char[] 24 25 26 27 28 29 private static String randomString(int length) { char[] buf = new char[length]; for (int i=0; i<length; i++) { buf[i] = chars[random.nextInt(chars.leng } return new String(buf); Source: PasswordGenerator.java  y y - , h t e y r s - e arch proxy ogram ele- h.random), d to match ust extract ded in the turned by generator ., answers ery gener- rch engine How to create random string with random characters? dling ns Util Package tions ns s Questions Programs eb Services Program: How to create random string with random characters? Description: Write a program to generate random string of length 10 charactors. Every time you call the method, the program should generate random string. Code: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 package com.java2novice.random;   import java.util.Random;   public class MyStringRandomGen {       private static final String CHAR_LIST =          "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";     private static final int RANDOM_STRING_LENGTH = 10;           /**      * This method generates random string      * @return      */     public String generateRandomString(){                   StringBuffer randStr = new StringBuffer();         for(int i=0; i<RANDOM_STRING_LENGTH; i++){             int number = getRandomNumber();             char ch = CHAR_LIST.charAt(number);             randStr.append(ch);         }         return randStr.toString();     }           /**      * This method generates random numbers      * @return int      */     private int getRandomNumber() {         int randomInt = 0;         Random randomGenerator = new Random(); Be the first of your friends to like this Java Sample Programs 7,256 likes Like Page ? Random string generation posted 10/13/2004 1:55 AM  posted 10/13/2004 2:15 AM A friendly place for programming greenhorns! Big Moose Saloon   Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies  Register / Login  Win a copy of Introducing JavaFX 8 Programming this week in the JavaFX forum! JavaRanch » Java Forums » Java » Java in General   Author Random string generation Anna Hays  Ranch Hand  Joined: Nov 09, 2003 Posts: 131  Hi, can Java generate a string of random charactors? I need a password generation. Can someone give me an idea of what's the proper way of doing this please? Thanks. Michael Dunn  Ranch Hand  Joined: Jun 09, 2003 Posts: 4632  This might be one way 1 2 3 4 5 6 7 8 9 10 11 12 13 14 class Testing {   public Testing()   {     final int PASSWORD_LENGTH = 8;     StringBuffer sb = new StringBuffer();     for (int x = 0; x < PASSWORD_LENGTH; x++)     {       sb.append((char)((int)(Math.random()*26)+97));     }     System.out.println(sb.toString());   }   public static void main(String[] args){new Testing();} } ? How to Generate Words Randomly in Java How to Add Buttons and Text to Your JavaFX Project Making Your Page Layouts Easier with Includes Create a Java How to Generate Words Randomly in Java By Barry Burd from Beginning Programming with Java For Dummies, 4th Edition Most Java programs don’t work correctly the first time you run them, and some programs don’t work w error on your part. This code is a case in point. To write this code, you need a way to generate three­letter words randomly. This code would give you anAccount.lastName = "" + (char) (myRandom.nextInt(26) + 'A') + (char) (myRandom.nextInt(26) + 'a') + (char) (myRandom.nextInt(26) + 'a');   10 easy tricks to learn any language from a man who speaks 9 Promoted by Babbel Unique Method May Regrow Lost Hair Promoted by Lifestyle Journal Seven Foods That Fight Inflammation and Belly Fat ­ For Dummies The  Plan Sam Wom   Random word from array list     while (line != null){       words.add(line);       //line = reader.readline();     }   }   public static void getRandomWord(){ Random rand = new Random(); String randomWord = words.get(rand.nextInt(words.size)); } } java random arraylist asked Dec 3 '13 at 18:35 user3062703 1 1 1     – So you're trying to get a random word from a file and output it? Tatakai Wasumi Dec 3 '13 at 18:49     –  Member variables (e.g. 'words') cannot be referenced from static methods (e.g. 'getRandomWord()'). Either declare 'words' as static or remove 'static' keyword from method signature. Hollis Waite Dec 3 '13 at 18:49     – you should use something like : int rand= minimum + (int)(Math.random()*maximum); Clad Clad Dec 3 '13 at 18:50     – Try this link maybe it will help you here Tatakai Wasumi Dec 3 '13 at 18:52     –  @TatakaiWasumi Indeed. From what I understand the first part of my code takes words from a file and puts them in an arraylist. The second part of my code needs to generate a random number and from that, output the corresponding word in the arraylist. I'm having issues with the fact that words is private... Says I can't reach it from getRandomWord user3062703 Dec 3 '13 at 18:57 1 Answer This will help you I think It's able to get a random word from an array of strings private static String[] names = { "Terminator", "Slicer","Ninja", "cow", "Robot",  "littlegirl" }; Generating random words of a certain length in java? 2 Answers What kind of words do you want to generate? Random lowercase characters? String getRandomWord(int length) { want to generate? Random lowercase characters? gth) { • In case the query is augmented, granularity is further controlled since the structural code entities matched • terms, excluding stop words, in the user free-form query (cf. Figure 6(a)) are kept, after stemming, in the aug- mented query (cf. Figure 6(c), lines Bissyande IxJ) • structural code entities collected from Q&A snippets (cf. Figure 6(b)) are mentioned with their type (e.g., non-qualified/partially qualified method invocation, or class) in the augmented query (cf. Figure 6(c), lines Bissyande IxJ) To accelerate code query generation, CoCaBu builds on an index of posts. Typically, Q&A forums provide archives of their posts. These posts are often formatted by a struc- tural language such as XML. For example, in Stack Over- flow posts, code snippets are enclosed in <code> ...</code>. As shown in Figure 8, our approach takes pre-downloaded posts from a Q&A site and extracts metadata (post ID, ques- tion title) and code snippets for each post. Each code snip- pet is then analyzed to retrieve the structural code entities. This phase presents challenges that will be addressed in Sec- tion 3.1. Q&A Posts Code
 Metadata Post Analyzer Snippet Index pq_method_invocation:Random.nextInt pq_method_invocation:Math.random class:word class:char class:int class:String class:Random instance:String instance:Random nq_method_invocation:nextInt code:gener code:random code:word ... Figure 7: Augmented query corresponding to the snippet shown in Figure ??. in Table 1: • terms, excluding stop words, in the user free-form query (cf. Figure 6(a)) are kept, after stemming, in the aug- (3) Searching for Code Examples 29

×