Java Code for Insult Generator

In summary: And certainly, this is not the only example of a simple, beautiful scheme solution to practical problems, that you can show to students early on.In summary, creating insult sentences is the task at hand. The professor gave us some code and functions to use, and we have to fill in the functions to make the program work. The program uses a grammar and randomly selects expansions to create the insult sentences. The code given includes functions such as selectExpansion and generateSentence, and the student is currently trying to fix errors and complete the program. However, the code given is messy and the student is struggling to understand it, and it would be much simpler if they were using a higher level language such as Scheme.
  • #1
royboyz12
6
0
Hi, I have to do a homework assignment for my intro to computer porgramming class and i have to write a program that creates insult sentences. My professor gave us some code to start with and we had to fill in the functions(professor gave us the names of these functions and the name of the program loop). I need help getting the function to work. I included the code i was given and below that i put the functions and what i did so far.


This is the code I was given:


Code:
import java.util.Random ;


public class Generator {

  public static void main(String[] args) {
    for (int n = 0 ; n < 10 ; n++) {
      System.out.println( generateSentence("S") ) ;
    }
  }

  ... PUT YOUR OTHER FUNCTIONS HERE ...


  /// The method selectExpansion(Category) will randomly expand
  /// Category according to the following grammar.  Returns "error" if
  /// there is no expansion.

  static Random RANDOM = new Random() ;

  static String[] GRAMMAR = {
    "S -> NAME VP",
    "VP -> V NP",
    "NP -> ART NN",
    "NN -> ADJ NN",
    "NN -> N",
    "ART -> a",
    "V -> is",
    "V -> looks like",
    "V -> acts like",
    "NAME -> dr aronis",
    "NAME -> mr aronis",
    "NAME -> john aronis",
    "ADJ -> stupid",
    "ADJ -> geeky",
    "ADJ -> ugly",
    "N -> idiot",
    "N -> teacher",
    "N -> fool"
  } ;

  public static String selectExpansion(String category) {
    // Variables:
    String thisRule = "", ruleLHS = "", ruleRHS = "" ;
    int numberOfExpansions = 0, expansionToUse = 0 ;
    // Count expansions for category:
    for (int n = 0 ; n < GRAMMAR.length ; n++) {
      thisRule = GRAMMAR[n] ;
      ruleLHS = thisRule.substring(0,thisRule.indexOf(" -> ")) ;
      if ( ruleLHS.equals(category) ) numberOfExpansions++ ;
    }
    // Return error if no expansions:
    if ( numberOfExpansions == 0 ) return "error" ;
    // Randomly select which expansion to use:
    expansionToUse = Math.abs(RANDOM.nextInt() % numberOfExpansions) ;
    // Go through rules while counting down through expansions of category,
    // and break with selected expansion:
    for (int n = 0 ; n < GRAMMAR.length ; n++) {
      thisRule = GRAMMAR[n] ;
      ruleLHS = thisRule.substring(0,thisRule.indexOf(" -> ")) ;
      ruleRHS = thisRule.substring(thisRule.indexOf(" -> ") + 4) ;
      if ( ruleLHS.equals(category) && (expansionToUse == 0) ) break ;
      if ( ruleLHS.equals(category) ) expansionToUse-- ;
    }
    return ruleRHS ;
  }

}

// End-of-File



I have to fill in the functions(function names were given) and this is what I did so far(i know i probably did some stuff wrong plus i need to add some more code...but I am just not sure what):

Code:
 public static void generateSentence(String insult){
    string insult;
    string left;
    string right;
    while(hasCategory(insult)){
      Category = firstCategory(insult);
      left = beforeFirstCategory(insult);
      right = afterFirstCategory(insult);
      insult = left + selectExpansion(Category) + right;
    }
  }
  
  public static boolean hasCategory(String s){
    for(int i=0; i<=s.length(); i++){
      if(charAt(i)>='A' && charAt(i)<='Z'){
        return true;
      }
    }  
    return false;
  }
  
  public static int beginningOfCategory(String s){
    for(int i=0; i<s.length(); i++){
      if(charAt(i)>='A' && charAt(i)<='Z'){
        return i;      
      }
    }
  }
  
  public static int endOfCategory(String s){
    for(int i=0; i<s.length(); i++){
      if(!(charAt(i)>'A' && charAt(i)<='A')){
        return i;   
      }
    }
  }
      
  public static String beforeFirstCategory (String s){
    beginningOfCategory(String s);
    return s.substring(0,beginningOfCategory(String s));
  }   
              
  public static String firstCategory(String s){
    beginningOfCategory(String s);
    endOfcategory(String s);
    return s.substring(beginningOfCategory(String s),endOfCategory(String s));
  }
  
  public static String afterFirstCategory(String s){
   endCategory(String s);
   s.length();
   return s.substring(endOfCategory(String s),s.length());
  }
 
Technology news on Phys.org
  • #2
You're almost there.

Code:
public static int endOfCategory(String s){
    for(int i=0; i<s.length(); i++){
      if(!(charAt(i)>'A' && charAt(i)<='A')){      // <---- N.B.
        return i;   
      }
    }
  }

This line doesn't work: (e > 'A' && e <= 'A') is never true, for any expression e, it's a contradiction.

What is the test you want, for endOfCategory? When you find a nonterminal (a 'category'), represented as a string of all-capital letters, at what point does it end?

"abc DEF ghi"

Take a short example string (like this one), and work out where the nonterminal is, where it starts and ends. Then take what you're doing, and generalize it. If your algorithm works on any string, it will also work on this particular, simple string: it's a test.
 
  • #3
(rayboyz, this part won't help you at all, you can safely ignore it)

To those PF'ers who think Scheme/Lisp is a bad language for teaching programming, that you should teach language used in industry right away (otherwise you're wasting time), take a look at the instructor's code here. This is a very good example. The problem here is a very simple, almost beautiful idea - generating sentences to follow a grammar. Though it is a simple problem, it has been overwhelmed, drowned in irrelevant implementation details - an absolute mess of string manipulation. Instead of solving the problem itself, poor 'royboyz' is spending all his work stuff like <= comparisons of ASCII characters with 'A'/'Z', to test case. This stuff couldn't be farther away from the real problem, whose main solution ('selectExpansion') is so messy that it's just given as a black box, because the instructor didn't trust their students to solve it (within the constraints of C-like code). 'Royboyz' completely misses out on the meat of the problem - he or she is unfairly deprived.

Instead, the SICP type approach with Scheme works at a much higher level of language than machine details: it deals directly with symbolic manipulation. This makes this exact problem here, far simpler, shorter, and directly accessible to new students. Take a look at the lisp solution: it was written by Peter Norvig (currently Director of Research at Google), in his book "Paradigms of Artificial Intelligence Programming". (There are two versions, one simple and one improved). And apparently you read the whole chapter online (edit: no, just parts of it), in the Google Books preview (it is chapter 2, "a simple lisp program"):

http://norvig.com/paip/simple.lisp

http://norvig.com/paip.html

http://books.google.com/books?id=QzGuHnDhvZIC&pg=PA34&source=gbs_search_s&cad=0

http://img171.imageshack.us/img171/420/41y2fdaae4l.jpg If this isn't eye-opening enough by itself, bear in mind this solution predates the Java language which the OP is written in.
 
Last edited by a moderator:

1. How does the Java code for Insult Generator work?

The Java code for Insult Generator works by randomly selecting words or phrases from different categories (e.g. adjectives, nouns, verbs) and combining them together to create unique insults. The code also includes methods for generating insults with different levels of intensity.

2. Can the Java code for Insult Generator be customized?

Yes, the code can be customized by adding or removing words from the existing categories or by creating new categories. This allows for a wider range of insults to be generated.

3. Is the Java code for Insult Generator user-friendly?

The code can be made user-friendly by incorporating a user interface or creating a web-based application. However, the code itself may require some basic knowledge of Java programming to understand and modify.

4. Are there any limitations to the Java code for Insult Generator?

The limitations of the code depend on how it is designed and implemented. Some potential limitations could include a limited number of word choices, repetitive insults, or difficulty in generating insults with specific themes or contexts.

5. Can the Java code for Insult Generator be used for any other purposes?

While the code is specifically designed for generating insults, it can also be modified and repurposed for other applications that require random text generation, such as creating randomized passwords or generating content for games.

Similar threads

  • Programming and Computer Science
Replies
8
Views
1K
  • Programming and Computer Science
Replies
10
Views
1K
  • Programming and Computer Science
Replies
8
Views
1K
  • Programming and Computer Science
Replies
8
Views
1K
  • Programming and Computer Science
Replies
22
Views
2K
  • Programming and Computer Science
Replies
1
Views
881
  • Programming and Computer Science
Replies
1
Views
872
  • Programming and Computer Science
Replies
2
Views
1K
  • Programming and Computer Science
Replies
7
Views
2K
  • Programming and Computer Science
Replies
1
Views
1K
Back
Top