Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

!!!!!!!Java!!!!! When you are confident that your methods work properly and that you can generate random text with my generateText method, you can move on

!!!!!!!Java!!!!! When you are confident that your methods work properly and that you can generate random text with my generateText method, you can move on to the second step.

Create a third class called Generator within the cs1410 package. Make class.

This class should have a main method that provides a user interface for random text generation. Your interface should work as follows: Main should bring up an input dialog with which the user can enter the desired analysis level .

The user should be repeatedly prompted until he or she enters an integer zero or higher.

If the user cancels the dialog, the program should end. It should bring up an input dialog with which the user can enter the desired length of the output text.

The user should be repeatedly prompted until he or she enters an integer zero or higher.

If the user cancels the dialog, the program should end. It should bring up a file dialog with which the user can select a text file to be analyzed.

The user should be repeatedly prompted until he or she selects a file that can be opened. If the user cancels the dialog at any point, the program should end.

If the text file turns out to contain fewer than level+1 characters, an appropriate error message should be displayed and then the program should end.

It should use the generateText method and the three inputs provided by the user to generate random text. It should use a message dialog to display the generated text.

The program should then end. Your program should handle gracefully all user errors. Under no circumstances should the program crash because of an unhandled exception.

current code -----

package cs1410;

import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.NoSuchElementException; import java.util.Random; import java.util.Scanner; import cs1410lib.Dialogs;

/** * A library of methods for implementing the random text generation algorithm described in PS5, Fall 2017. * */ public class PS5Library { /** * Demonstrates the use of the generateText method. */ public static void main (String[] args) throws IOException { // You won't need to use this feature in PS5, but this shows how to include a resource (in this // case a text file) as part of a project. I created a package called "books", then put two // text files into the package. I was then able to open one of those files as shown below. When // I export the project, the resources go along with it.

// get text book, and make Scanner to consume token. try (InputStream book = PS5Library.class.getResourceAsStream("/books/PrideAndPrejudice.txt"); Scanner input = new Scanner(book)) { System.out.println(generateText(input, 6, 100)); }

}

/** * Uses all the text in the input to generate and return random text with the specified level and length, using the * algorithm described in PS5, CS 1410, Fall 2017. * * @throws IllegalArgumentException if level < 0, or length < 0, or there are less than level+1 chars in the input. */ public static String generateText (Scanner input, int level, int length) { // Validate the parameters if (level < 0 || length < 0) { throw new IllegalArgumentException(); }

// Grab all the text from the Scanner and make sure it is long enough. String text = scannerToString(input); if (level >= text.length()) { throw new IllegalArgumentException(); }

// Create a random number generator to pass to the methods that make random choices Random rand = new Random();

// Get the initial pattern. String pattern = chooseSubstring(text, level, rand);

// Build up the final result one character at a time. We use a StringBuilder because // it is more efficient than using a String when doing long sequences of appends. StringBuilder result = new StringBuilder(); while (result.length() < length) { try { // Pick at random a character that follows the pattern in the text and append it // to the result. If there is no such character (which can happen if the pattern // occurs only once, at the very end of text), the method we're calling will throw // a NoSuchElementException, which is caught below. char newChar = pickCharThatFollowsPattern(text, pattern, rand); result.append(newChar);

// Update the pattern by removing its first character and adding on the new // character. The length of the pattern remains the same. If the pattern is // the empty string, though, it never changes.) if (pattern.length() > 0) { pattern = pattern.substring(1) + newChar; } } catch (NoSuchElementException e) { // It is possible to get stuck if the pattern occurs only once in the text and // that occurrence is at the very end of the text. In this case, we pick a new // seed and keep going. pattern = chooseSubstring(text, level, rand); } }

// Return the string we've accumulated. return result.toString(); }

/* * getCharsThatFollowPattern, which takes a String text and a String pattern as parameters, and returns an * ArrayList. The returned list should contain the character that follows each non-tail occurrence of the * pattern in the text. (A non-tail occurrence of the pattern is one that is not at the very end of the text.) The * length of the list must be the same as the number of non-tail occurrences of the pattern. The character stored at * index n of the list must be the character that followed the nth non-tail occurrence of the pattern. For example, * getCharsThatFollowPattern("abcabdabcab", "ab") should return the ArrayList ['c', 'd', 'c']. * * To implement this method, use one of the indexOf methods provided by String objects. */

public static ArrayList getCharsThatFollowPattern (String text, String pattern) { // Make new array to handle as value. ArrayList list = new ArrayList<>();

int start = 0;

// loop end when is true while (true) {

int index = text.indexOf(pattern, start);

// handle error if (index <= -1) {

break;

}

if (index + pattern.length() == text.length()) {

// Sequence of tail

break;

}

list.add(text.charAt(index + 1));

start = index + 1;

}

return list;

}

/* * pickCharThatFollowsPattern, which takes a String text, a String pattern, and a random number generator as * parameters. It should randomly choose a non-tail occurrence of the pattern in the text, returning the character * that immediately follows that occurrence of the pattern. If there are no non-tail occurrences of the pattern in * the text, the method should throw a NoSuchElementException. For example, * pickCharThatFollowsPattern("They are here", "he") should return 'y' or 'r' with equal probability. * * You should use your getCharsThatFollowPattern method in your implementation of this method. If you don't, you'll * be wasting a lot of time. */

public static char pickCharThatFollowsPattern (String text, String pattern, Random rand) { // Make new arrayList ArrayList tailChars = getCharsThatFollowPattern(text, pattern);

// if statement to handle error if (tailChars.isEmpty()) // . { throw new NoSuchElementException(); } else { return tailChars.get(rand.nextInt(tailChars.size())); } }

/* * chooseSubstring, which takes a String text, an int length, and a random number generator as its parameters. It * should use the random number generator to return a randomly chosen substring of text that has the specified * length. If length is either negative or greater than the length of text, the method should throw an * IllegalArgumentException. For example, chooseSubstring("abcde", 4, new Random()) should return "abcd" about half * the time and "bcde" about half the time. * * A string of length n will contain n+1-m different substrings of length m, assuming n m. These substrings start * at indexes ranging from 0 to n-m. There is a convenient method provided by the Random parameter that you can use * to choose a random index. * */ public static String chooseSubstring (String text, int length, Random rand) { // if statement to handle error if (length < 0 || length > text.length()) {

throw new IllegalArgumentException();

} else { int startIndex = rand.nextInt(text.length() - length + 1);

return text.substring(startIndex, startIndex + length); } }

/* * scannerToString, which takes a Scanner as its parameter and returns a String. The returned string consists of all * the characters in the scanner in their original order, including the newlines. The last line (assuming there are * any lines) should always end with a newline, even if it didn't in the original text. For example, * scannerToString("This is a test") should return "This is a test ". * * A convenient way to implement this method is to build up the result by reading one line at a time from the * Scanner. For much improved efficiency when dealing with Scanners containing complete books, consider using a * StringBuilder object to construct the result. You can look at my generateText method for an example of its use. */

public static String scannerToString (Scanner input) {

String result = "";

if (!input.hasNext()) { throw new NoSuchElementException(); } while (input.hasNext()) { result += input.nextLine() + " "; }

return result;

} }

Test code -----

import static org.junit.Assert.*; import java.util.ArrayList; import java.util.NoSuchElementException; import java.util.Random; import java.util.Scanner; import org.junit.Test;

public class PS5LibraryTests { /** * This checks that the last line of the result ends with a newline, even if the last line in the scanner didn't. */ @Test public void testScannerToString1 () { assertEquals("This is a test ", PS5Library.scannerToString(new Scanner("This is a test"))); }

/** * This illustrates how to test that an exception is thrown when one is supposed to be thrown. If * pickCharThatFollowsPattern doesn't thrown the right kind of exception, the test will fail. */ @Test(expected = NoSuchElementException.class) public void testPickCharThatFollowsPattern () { PS5Library.pickCharThatFollowsPattern("hello", "o", new Random()); }

/** * This illustrates a way to do tests of methods that have a randomized behavior. When we ask for a randomly chosen * substring of length 4 of "abcde", about half the time we should get "abcd" and about half the time we should get * "bcde". So we call chooseSubstring 1000 times and count how many times we get each possibility. (If we get * anything else back, we immediately fail the test case.) Then we assert that we got each "about" half the time. It * is possible for a correct implementation to fail this test if we get extremely unlucky, but that is extremely * unlikely. */ @Test public void testChooseSubstring () { Random rand = new Random(); int abcd = 0; int bcde = 0;

for (int i = 0; i < 1000; i++) { String substring = PS5Library.chooseSubstring("abcde", 4, rand); if (substring.equals("abcd")) { abcd++; } else if (substring.equals("bcde")) { bcde++; } else { fail(); } }

assertTrue(400 <= abcd && abcd <= 600 && 400 <= bcde && bcde <= 600); }

/** * This illustrates how to make assertions about ArrayLists. */ @Test public void testGetCharsThatFollowPattern () { ArrayList list = new ArrayList(); list.add('b'); list.add('b'); assertEquals(list, PS5Library.getCharsThatFollowPattern("abababa", "aba")); }

}

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Database Systems For Advanced Applications 27th International Conference Dasfaa 2022 Virtual Event April 11 14 2022 Proceedings Part 2 Lncs 13246

Authors: Arnab Bhattacharya ,Janice Lee Mong Li ,Divyakant Agrawal ,P. Krishna Reddy ,Mukesh Mohania ,Anirban Mondal ,Vikram Goyal ,Rage Uday Kiran

1st Edition

3031001257, 978-3031001253

More Books

Students also viewed these Databases questions