Question

In: Computer Science

Part 3: Anagram Arranger (20 pts) Overview Create a file called Anagram.java, which reads a series...

Part 3: Anagram Arranger (20 pts)

Overview

  • Create a file called Anagram.java, which reads a series of words input from a file.
  • For each word read from the file, the user will have the option to swap letters within that word.
  • You are required to use your doubly-linked list class to receive credit for this part of the assignment.
  • Therefore, your word should be stored as a List of Characters or Strings (each String being one letter).
  • After the user has rearranged the word, it should be written to a file, including the changes the user has made.

Specifications

  • The program should welcome the user with the message Welcome to the Anagram Arranger!
  • It should then prompt the user to enter the name of a file.
  • Provided the user enters a correct file name (see section regarding error checking below), then the program will read in all of the words in the file, one-by-one.
  • Each word should be stored in a List of Characters or Strings (each String being one letter).
  • It will display the word, along with its corresponding number, with the message:  Word #<count> is <word>
  • See below for examples.
  • The user will then be prompted to enter the position of two different letters in the word that the user wants to be swapped.
  • The program will verify the user choice by re-printing the word with carrots beneath the selected letters.
  • The user will then be required to confirm his or her choice with the message: Enter the position numbers of the two letters you wish to swap:
    • The program should accept four different input options from the user -- y, Y, yes, and Yes -- to indicate consent.
  • If the user indicates "no", the word will be reprinted with a prompt to enter the position of two different letters.
  • If the user enters yes, then the program should swap the two selected letters, and then prompt the user to indicate whether he or she would like to swap additional letters in the word.
    • The program should accept four different input options from the user -- y, Y, yes, and Yes -- to indicate consent.
  • The user should be able to continue swapping letters indefinitely.
  • Once the user no longer wishes to swap, the current version of the word should be written to a file named output.txt
  • Please see below for an incomplete example run:

Welcome to the Anagram Arranger!

Please enter the name of your input file: spooky.txt

Word #1 is zombie
1: z
2: o
3: m
4: b
5: i
6: e

Enter the position numbers of the two letters you wish to swap: 1 2

z o m b i e
^ ^  
Are these the letters you wish to swap? (y/n): y

The new word is: o z m b i e

Want to keep rearranging? (y/n): y

1: o
2: z
3: m
4: b
5: i
6: e

Enter the position numbers of the two letters you wish to swap: 3 5

o z m b i e
    ^   ^        
Are these the letters you wish to swap? (y/n): y

The new word is: o z i b m e

Want to keep rearranging? (y/n): n

Word #2 is mummy
1: m
2: u
3: m
4: m
5: y

Enter the position numbers of the two letters you wish to swap:  etc...

A complete Example:

This example assumes an input file named words.txt with the following content - however, the user should be able to enter any file name and the file can contain any number of words:

Spring
Summer
Fall
Winter

Output of running Anagram.java

Welcome to the Anagram Arranger!

Please enter the name of your input file: abc.txt

Sorry. I cannot find a file by that name!
Please enter the name of a valid input file: 123.txt

Sorry. I cannot find a file by that name!
Please enter the name of a valid input file: words.txt

Word #1 is Spring
1: S
2: p
3: r
4: i
5: n
6: g

Enter the position numbers of the two letters you wish to swap: 3 5

S p r i n g
    ^   ^       
Are these the letters you wish to swap? (y/n): y

The new word is: S p n i r g

Want to keep rearranging? (y/n): yes

1: S
2: p
3: n
4: i
5: r
6: g

Enter the position numbers of the two letters you wish to swap: 1 6

S p n i r g
^         ^         
Are these the letters you wish to swap? (y/n): yes

The new word is: g p n i r S

Want to keep rearranging? (y/n): n

Word #2 is Summer
1: S
2: u
3: m
4: m
5: e
6: r

Enter the position numbers of the two letters you wish to swap: 2 3

S u m m e r
^ ^   
Are these the letters you wish to swap? (y/n): Yes

The new word is: S m u m e r

Want to keep rearranging? (y/n): Yes

1: S
2: m
3: u
4: m
5: e
6: r

Enter the position numbers of the two letters you wish to swap: 4 5

S m u m e r
      ^ ^       
Are these the letters you wish to swap? (y/n): y

The new word is: S m u e m r

Want to keep rearranging? (y/n): n

Word #3 is Fall
1: F
2: a
3: l
4: l

Enter the position numbers of the two letters you wish to swap: 1 2

F a l l
^ ^
Are these the letters you wish to swap? (y/n): y

The new word is: a F l l

Want to keep rearranging? (y/n): n

Word #4 is Winter
1: W
2: i
3: n
4: t
5: e
6: r

Enter the position numbers of the two letters you wish to swap: 1 3

W i n t e r
^   ^   
Are these the letters you wish to swap? (y/n): n
1: W
2: i
3: n
4: t
5: e
6: r

Enter the position numbers of the two letters you wish to swap: 1 4

W i n t e r
^     ^     
Are these the letters you wish to swap? (y/n): y

The new word is: t i n W e r

Want to keep rearranging? (y/n): y

1: t
2: i
3: n
4: W
5: e
6: r

Enter the position numbers of the two letters you wish to swap: 2 5

t i n W e r
^     ^       
Are these the letters you wish to swap? (y/n): y

The new word is: t e n W i r

Want to keep rearranging? (y/n): y

1: t
2: e
3: n
4: W
5: i
6: r

Enter the position numbers of the two letters you wish to swap: 3 4

t e n W i r
    ^ ^     
Are these the letters you wish to swap? (y/n): y

The new word is: t e W n i r

Want to keep rearranging? (y/n): n

Bye!

Corresponding output.txt for above example:

g p n i r S
S m u e m r
a F l l
t e W n i r

Required Error Checking

  • Your Anagram.java should also do error checking for the following cases only:
  1. The user inputs a position number that is higher than the position of the last character in the word
  2. The user reverses the order of the two positions by giving the higher number followed by the lower number
  3. The user enters the same position number twice.
  • For the above errors, the program should print the message Invalid entry! and allow the user to try again, as shown in the example below.
  • Additionally, the program should correctly handle the below error:
  1. The user enters an incorrect name for a file.
    1. Error checking should be completed using a loop to handle multiple invalid inputs
    2. Error message must be:

Sorry. I cannot find a file by that name!
Please enter the name of a valid input file:

  • Please see below for examples of how to handle invalid input.


Error Checking Example:

Welcome to the Anagram Arranger!

Please enter the name of your input file: ddd.txt

Sorry. I cannot find a file by that name!
Please enter the name of a valid input file: nnn.txt

Sorry. I cannot find a file by that name!
Please enter the name of a valid input file: splooky.txt

Sorry. I cannot find a file by that name!
Please enter the name of a valid input file: spooky.txt

Word #1 is zombie
1: z
2: o
3: m
4: b
5: i
6: e

Enter the position numbers of the two letters you wish to swap: 4 2

Invalid entry!

1: z
2: o
3: m
4: b
5: i
6: e

Enter the position numbers of the two letters you wish to swap: 1 10

Invalid entry!

1: z
2: o
3: m
4: b
5: i
6: e

Enter the position numbers of the two letters you wish to swap: 2 2

Invalid entry!

1: z
2: o
3: m
4: b
5: i
6: e

Enter the position numbers of the two letters you wish to swap: 2 3

z o m b i e
^ ^    
Are these the letters you wish to swap? (y/n): yes

The new word is: z m o b i e

Want to keep rearranging? (y/n): etc.

Solutions

Expert Solution

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;

public class Anagram {
private static final String FILENAME = "anagram_words.txt";
  
public static void main(String[] args) {
  
ArrayList<String> words = readWordsFromFile(FILENAME);
for(int i = 0; i < words.size(); i++)
{
String word = words.get(i);
System.out.println("Word #" + (i + 1) + " is " + word + "\n");
performAnagram(word);
System.out.println();
}
System.out.println("Bye!");
System.exit(0);
}
  
private static ArrayList<String> readWordsFromFile(String filename)
{
ArrayList<String> words = new ArrayList<>();
Scanner fileReader;
try
{
fileReader = new Scanner(new File(filename));
while(fileReader.hasNextLine())
{
words.add(fileReader.nextLine().trim());
}
fileReader.close();
}catch(FileNotFoundException fnfe){
System.out.println(filename + " could not be found! Exiting..");
System.exit(0);
}
return words;
}
  
private static void performAnagram(String s)
{
char continueChoice = 0;
do
{
Scanner sc = new Scanner(System.in);
char chars[] = s.toCharArray();
for(int i = 0; i < chars.length; i++)
System.out.println((i + 1) + ": " + chars[i]);

System.out.print("Enter the position numbers of the two letters you wish to swap: ");
String str = sc.nextLine().trim();
String[] posData = str.split(" ");
int pos1 = Integer.parseInt(posData[0]) - 1;
int pos2 = Integer.parseInt(posData[1]) - 1;
if(pos1 < 0)
pos1 = 0;
if(pos2 < 0)
pos2 = 0;
if(!(pos1 >= 0 && pos1 <= str.length() - 1) && !(pos2 >= 0 || pos2 <= str.length() - 1))
System.out.println("Invalid entry!\n");
else
{
String modStr = s + "\n" + getIndicator(s.length(), pos1, pos2);
System.out.println(modStr);
System.out.print("Are these the letters you wish to swap? (y/n): ");
char swapChoice = sc.nextLine().trim().charAt(0);
if(swapChoice == 'N' || swapChoice == 'n')
continue;
// if yes
String swappedStr = swapStr(s, pos1, pos2);
System.out.println("The new word is: " + swappedStr);
s = swappedStr;
  
System.out.print("\nWant to keep rearranging? (y/n): ");
continueChoice = sc.nextLine().trim().charAt(0);
if(continueChoice == 'N' || continueChoice == 'n')
break;
System.out.println();
}
}while(continueChoice != 'N' || continueChoice != 'n');
}
  
private static String swapStr(String s, int pos1, int pos2)
{
String newStr = "";
char chars[] = s.toCharArray();
char temp = chars[pos1];
chars[pos1] = chars[pos2];
chars[pos2] = temp;
for(int i = 0; i < chars.length; i++)
newStr += chars[i];
return newStr;
}
  
private static String getIndicator(int len, int pos1, int pos2)
{
String newStr = "";
for(int i = 0; i < len; i++)
{
if(i == pos1 || i == pos2)
newStr += "^";
else
newStr += " ";
}
return newStr;
}
}

********************************************************* SCREENSHOT *******************************************************

INPUT FILE (angram_words.txt) - This file needs to be created before running the code and this code should be created within the same project directory where the above Anagram.java file will be residing.

CONSOLE OUTPUT :


Related Solutions

Write a program that reads a file called document.txt which is a text file containing an...
Write a program that reads a file called document.txt which is a text file containing an excerpt from a novel. Your program should print out every word in the file that contains a capital letter on a new line to the stdout. For example: assuming document.txt contains the text C++
Using Python 3 Write a function reads the file called simpleinterest.txt. Each row in simpleinterest.txt is...
Using Python 3 Write a function reads the file called simpleinterest.txt. Each row in simpleinterest.txt is a comma seperated list of values in the order of PV, FV, n, r. For each row, there is one value missing. Write an output file that fills in the missing value for each row.
Overview: You will write a program that reads up to 100 numbers from a file. As...
Overview: You will write a program that reads up to 100 numbers from a file. As you read the numbers, insert them into an array in ascending order. Specifics: 1A. Write a function called insertIntoSortedArray . i. It should take three arguments - a. myArray[ ] : sorted array that should be able to hold at most 100 integers. b. numEntries : the number of elements inserted so far. c. newValue : the incoming value to be inserted into the...
2. Write a program which reads in the text file generated in part one and writes...
2. Write a program which reads in the text file generated in part one and writes out the same data as a comma-separated values (CSV) file for further processing. The file should have a header line which identifies which column contains which values and should look something like this: Time, Potentiometer, Temperature, Light, Switch0, Switch1, Switch2, Switch3 That header line should be followed by detail lines containing the measurements and should look something like this (matching the above Arduino output):...
Create a Python program that: Reads the content of a file (Vehlist.txt) The file contains matching...
Create a Python program that: Reads the content of a file (Vehlist.txt) The file contains matching pairs of vehicle models and their respective makes Separate out the individual make and model on each line of the file Add the vehicle make to one list, and the vehicle model to another list; such that they are in the same relative position in each list Prompt the user to enter a vehicle model Search the list containing the vehicle models for a...
Write a program named FinalExamProgram2 that reads numbers from a file (which you will create using...
Write a program named FinalExamProgram2 that reads numbers from a file (which you will create using Notepad) into a one-dimensional array and then analyzes the numbers as described below. Your program must use loops to read the numbers into the array and to analyze the contents of the array. The program’s main function should do the following:  Read eight floating-point numbers from the file named numbers.txt into a onedimensional array, displaying each number on the screen.  Pass the...
This is C++ Create a program that reads an HTML file and converts it to plain...
This is C++ Create a program that reads an HTML file and converts it to plain text. Console: HTML Converter Grocery List * Eggs * Milk * Butter Specifications: The HTML file named groceries.html contains these HTML tags: <h1>Grocery List</h1> <ul> <li>Eggs</li> <li>Milk</li> <li>Butter</li> </ul> When the program starts, it should read the contents of the file, remove the HTML tags, remove any spaces to the left of the tags, add asterisks (*) before the list items, and display the...
Python File program 5: Word Frequencies (Concordance)    20 pts 1. Use a text editor to create...
Python File program 5: Word Frequencies (Concordance)    20 pts 1. Use a text editor to create a text file (ex: myPaper.txt) It should contain at least 2 paragraphs with around 200 or more words. 2. Write a Python program (HW19.py) that asks the user to provide the name of the text file. Be SURE to check that it exists! Do NOT hard-code the name of the file! Use the entry provided by the user! read from the text file NOTE:...
Create a project called rise. Add a class called GCD. Complete a program that reads in...
Create a project called rise. Add a class called GCD. Complete a program that reads in a numerator (as an int) and a denominator (again, as an int), computes and outputs the GCD, and then outputs the fraction in lowest terms. Write your program so that your output looks as close to the following sample output as possible. In this sample, the user entered 42 and 56, shown in green. Enter the numerator: 42 Enter the denominator: 56 The GCD...
Create a program that reads a file of 2D coordinates and calculates the bounding box and...
Create a program that reads a file of 2D coordinates and calculates the bounding box and center of the bounding box. The bounding box is defined as the minimum area that fully encompasses all the coordinates. The center of that bounding box is calculated by taking the mean of the bounding box coordinates: ( x1+x2 2 , y1+y2 2 ). • If the input file cannot be opened, warn the user by printing "CANNOT OPEN FILE." to stdout. • Print...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT