Question

!!!!!!!Java!!!!! When you are confident that your methods work properly and that you can generate random...

!!!!!!!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<Character>. 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<Character> getCharsThatFollowPattern (String text, String pattern)
{
// Make new array to handle as value.
ArrayList<Character> 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<Character> 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\nis a\ntest") should return "This\nis a\ntest\n".
*
* 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() + "\n";
}

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\nis a\ntest\n", PS5Library.scannerToString(new Scanner("This\nis a\ntest")));
}

/**
* 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<Character> list = new ArrayList<Character>();
list.add('b');
list.add('b');
assertEquals(list, PS5Library.getCharsThatFollowPattern("abababa", "aba"));
}

}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

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<Character>. 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<Character> getCharsThatFollowPattern (String text, String pattern)
{
// Make new array to handle as value.
ArrayList<Character> 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<Character> 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\nis a\ntest") should return "This\nis a\ntest\n".
*
* 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() + "\n";
}

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\nis a\ntest\n", PS5Library.scannerToString(new Scanner("This\nis a\ntest")));
}

/**
* 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<Character> list = new ArrayList<Character>();
list.add('b');
list.add('b');
assertEquals(list, PS5Library.getCharsThatFollowPattern("abababa", "aba"));
}

}

Add a comment
Know the answer?
Add Answer to:
!!!!!!!Java!!!!! When you are confident that your methods work properly and that you can generate random...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • my goal is to generate a random number every 10 seconds and store in arraylist. when...

    my goal is to generate a random number every 10 seconds and store in arraylist. when I generate the new number every 10 second I want to update the previous number from the arraylist. currently it gets the first number current num in main method but when I store after 10 second i'm not geting the update current number. NOTE: ***I want the Runnable to be in the arraylist method. Not in main method. my goal is to send the...

  • my goal is to generate a random number every 10 seconds and store in arraylist. when...

    my goal is to generate a random number every 10 seconds and store in arraylist. when I generate the new number every 10 second I want to update the previous number from the arraylist. currently it gets the first current number in main method but when I store after 10 second i'm not getting the update current number. I would appreciate any help. NOTE: ***I want the Runnable to be in the same class, Not in main method. my goal...

  • my goal is to generate a random number every 10 seconds and store in arraylist. when...

    my goal is to generate a random number every 10 seconds and store in arraylist. when I generate the new number every 10 second I want to update the previous number from the arraylist. currently it gets the first current number in main method but when I store after 10 second i'm not getting the update current number. I would appreciate any help. NOTE: ***I want the Runnable to be in the same class, Not in main method. my goal...

  • Java StringNode Case Study: Rewrite the following methods in the StringNode class shown below. Leave all...

    Java StringNode Case Study: Rewrite the following methods in the StringNode class shown below. Leave all others intact and follow similar guidelines. The methods that need to be changed are in the code below. - Rewrite the indexOf() method. Remove the existing recursive implementation of the method, and replace it with one that uses iteration instead. - Rewrite the isPrefix() method so that it uses iteration. Remove the existing recursive implementation of the method, and replace it with one that...

  • could you please help me with this problem, also I need a little text so I...

    could you please help me with this problem, also I need a little text so I can understand how you solved the problem? import java.io.File; import java.util.Scanner; /** * This program lists the files in a directory specified by * the user. The user is asked to type in a directory name. * If the name entered by the user is not a directory, a * message is printed and the program ends. */ public class DirectoryList { public static...

  • *JAVA* Can somebody take a look at my current challenge? I need to throw a different...

    *JAVA* Can somebody take a look at my current challenge? I need to throw a different exception when a)(b is entered. It should throw "Correct number of parenthesis but incorrect syntax" The code is as follows. Stack class: public class ArrayStack<E> {    private int top, size;    private E arrS[];    private static final int MAX_STACK_SIZE = 10;    public ArrayStack() {        this.arrS = (E[]) new Object[MAX_STACK_SIZE];        this.top = size;        this.size = 0;...

  • JAVA HELP: Directions Write a program that will create an array of random numbers and output...

    JAVA HELP: Directions Write a program that will create an array of random numbers and output the values. Then output the values in the array backwards. Here is my code, I am having a problem with the second method. import java.util.Scanner; import java.util.Random; public class ArrayBackwards { public static void main(String[] args) { genrate(); print(); } public static void generate() { Scanner scanner = new Scanner(System.in);    System.out.println("Seed:"); int seed = scanner.nextInt();    System.out.println("Length"); int length = scanner.nextInt(); Random random...

  • Use the Summation recursive program you did in the class to also work with minus integers....

    Use the Summation recursive program you did in the class to also work with minus integers. For example, the sum of -3 will be -6 which is (-3)+(-2)+(-1)+0. USE THIS CODE package project5; import java.util.Scanner; public class SingleRecursion { /** Main method */ public static long sum(int n) {    if (n<0) throw    new IllegalArgumentException ("Can't calculate factorial of negative");    if (n==1)        return 1;    else if (n==0)        return 1;    else       ...

  • Intro to Java - Assignment JAVA ASSIGNMENT 13 - Object Methods During Event Handling Assignment 13...

    Intro to Java - Assignment JAVA ASSIGNMENT 13 - Object Methods During Event Handling Assignment 13 Assignment 13 Preparation This assignment will focus on the use of object methods during event handling. Assignment 13 Assignment 13 Submission Follow the directions below to submit Assignment 13: This assignment will be a modification of the Assignment 12 program (see EncryptionApplication11.java below). Replace the use of String concatenation operations in the methods with StringBuilder or StringBuffer objects and their methods. EncryptTextMethods.java ====================== package...

  • Study the recursive instance method length()of MyLinkedList2 class and its associated auxiliary method. Then solve (a),...

    Study the recursive instance method length()of MyLinkedList2 class and its associated auxiliary method. Then solve (a), (b), and (c) below in a similar way: (a)   Convert the method public Element find(Object obj)of MyLinkedList2 class to a recursive one. Use an auxiliary private method. (b)   Convert the method public String toString( )of MyLinkedList2 class to a recursive one such that it returns the string representation of a linked list in the form: {ValueDatum1  valueDatum2 valueDatum3  . . .  valueDatumN-1   valueDatumN} Use an auxiliary private method....

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT