Java Insult Generator Code Issues?

  • Context: Java 
  • Thread starter Thread starter royboyz12
  • Start date Start date
  • Tags Tags
    Code Generator Java
Click For Summary
SUMMARY

The forum discussion centers on a Java program designed to generate insult sentences based on a defined grammar. The user, identified as "royboyz," is struggling to implement several functions required to complete the assignment. Key issues include incorrect string manipulation methods and logical errors in the category detection functions. The provided code snippet includes a grammar array and a method for selecting expansions, but the user needs to refine their functions for generating sentences and correctly identifying categories.

PREREQUISITES
  • Java programming fundamentals, including syntax and structure
  • Understanding of string manipulation in Java
  • Basic knowledge of grammar rules and parsing techniques
  • Familiarity with random number generation in Java using the Random class
NEXT STEPS
  • Refine the generateSentence function to correctly manipulate strings and generate sentences
  • Implement and test the endOfCategory function to accurately identify the end of a category
  • Explore Java's String methods for more efficient string handling
  • Review concepts of context-free grammars and their implementation in programming
USEFUL FOR

Students in introductory programming courses, Java developers looking to enhance their string manipulation skills, and anyone interested in natural language processing techniques.

royboyz12
Messages
6
Reaction score
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
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.
 
(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:

Similar threads

  • · Replies 8 ·
Replies
8
Views
2K
  • · Replies 1 ·
Replies
1
Views
1K
Replies
8
Views
3K
  • · Replies 10 ·
Replies
10
Views
3K
  • · Replies 22 ·
Replies
22
Views
4K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 8 ·
Replies
8
Views
2K
  • · Replies 1 ·
Replies
1
Views
1K
  • · Replies 7 ·
Replies
7
Views
2K
Replies
1
Views
2K