Question

In: Computer Science

CompSci 251 Assignment 1 Due Sep. 23rd, 2019 Create a program that will format long pieces...

CompSci 251

Assignment 1 Due Sep. 23rd, 2019

Create a program that will format long pieces of text based on user input. User input will determine the number of indents allowed for the first line in each paragraph, the number of characters allowed per line, and the number of sentences allowed per paragraph. There are three pieces of text, where each is a famous speech that is represented by a single String variable at the top of the base file.

Requirements

Your program must take user input and format one of the three speeches along the following criteria. See example run below for expected behavior and output.

 User input 1: Select one of the three speeches at the top of the file to format.
o If something is entered that is not one of the three speeches, inform the user and ask again until

a valid response is given.
o If no answer is given, meaning an empty string or a string with just spaces is entered, inform the

user and ask again until a valid response is given.
 User input 2: Select number of indents allowed for the first line in each paragraph. Range should be

between and include 0 – 2. Expect the user to only enter numbers or blank spaces.
o If number is not with in range, inform the user and ask again.
o If empty string or just spaces is entered, inform the user and ask again.
o Keep in mind an indent (or tab) does count towards the characters allowed per line. For my

console a single tab equals 8 characters.
 User input 3: Select number characters allowed per line when printed to the screen. Range should be

between and include 30 – 120. Expect the user to only enter blank spaces or numbers.
o If number is not within range, inform the user and ask again.
o If empty string or just spaces is entered, inform the user and ask again.
o The number of characters are not allowed to exceed the number selected for each line.
o Words are not allowed to be split between lines. This means if a word causes a single line to

exceed the max amount of characters, the word must be added to the next line.
o All periods, commas, question marks, exclamation points, and any other punctuation count

towards the total number of characters allowed per line.
 User input 4: Select number of sentences allowed per paragraph. Range should be between and include

3 – 8. Expect the user to only enter blank spaces or numbers.
o If number is not within range, inform the user and ask again.
o If empty string is entered, inform the user and ask again.
o A sentence ends with a period, question mark, or exclamation point.
o If there is more than one paragraph, the last paragraph is not required to have the specified

number of sentences. It gets whatever is left.

  •  After input 4 is entered, your program should print out the selected speech from input 1 to the console

    in the specified format based on inputs 2,3 and 4.

  •  Each speech should end with the writer’s name on a different line. Each name is precluded by “---” at

    the end of each string.

  •  User input 5: Would the user like to format another speech.

o If the user does not enter yes or no, inform the user and ask again.

o If empty string is entered, inform the user and ask again.A few extra comments

For all inputs, a user is not allowed to advance to the next input until the current input is valid based on the criteria listed above.

You are allowed to use Integer.ParseInt(String str) to convert a String number to an int number. It is ok if your program crashes using this code when converting a string to an int. Later in the course, we will discuss how to handle such cases using exceptions.

Example using Integer.ParseInt(String str)

String number = “5”;
int x = Integer.ParseInt(number); //This works and will convert a String to an int String notNumber = “hello”;
int y = Integer.parseInt(notNumber); //Crash

When complete, export your Java file to a zip folder and submit it to D2L.

Below is a sample run. I highlighted the user input. The first run is when the user enters everything with no errors. The second run shows how your program should respond when the user enters incorrect values. The third run is another example with no errors.

Please select a speech to format. Choices are Gettysburg, Washington, or Lou: Gettysburg"Gettysburg" is in my memory.
Please enter number of indents per first line, between 0-2: 1
"1" is a valid number.

Please enter number of characters allowed per line, between 30-120: 50"50" is a valid number.
Please enter number of sentences per paragraph, between 3-8: 4
"4" is a valid number.

Fourscore and seven years ago our fathers brought forth, on this continent, a new nation, conceived in liberty, and dedicated to the proposition that all men are created equal. Now we are engaged in a great civil war, testing whether that nation, or any nation so conceived, and so dedicated, can long endure. We are met on a great battle-field of that war. We have come to dedicate a portion of that field, as a final resting-place for those who here gave their lives, that that nation might live.

It is altogether fitting and proper that we should do this. But, in a larger sense, we cannot dedicate, we cannot consecrate—we cannot hallow—this ground. The brave men, living and dead, who struggled here, have consecrated it far above our poor power to add or detract. The world will little note, nor long remember what we say here, but it can never forget what they did here.

It is for us the living, rather, to be dedicated here to the unfinished work which they

who fought here have thus far so nobly advanced. It is rather for us to be here dedicated to the great task remaining before us—that from these honored dead we take increased devotion to that cause for which they here gave the last full measure of devotion—that we here highly resolve that these dead shall not have died in vain—that this nation, under God, shall have a new birth of freedom, and that government of the people, by the people, for the people, shall not perish from the earth.

---Abraham Lincoln
Is there another piece of text to format? (yes/no) yes

Please select a speech to format. Choices are Gettysburg, Washington, or Lou:
Sorry, that is not in my memory. Your choices are Gettysburg, Washington, or Lou:
You did not enter anything. Your choices are Gettysburg, Washington, or Lou: Washington "Washington" is in my memory.
Please enter number of indents per first line, between 0-2: <empty>
Sorry, you did not enter anything. Please enter a number between 0-2: 566456
The number entered is not within range. Please enter a number between 0-2: 1
"1" is a valid number.
Please enter number of characters allowed per line, between 30-120: 29
The number entered is not within range. Please enter a number between 30-120: <empty>Sorry, you did not enter anything. Please enter a number between 30-120: 150
The number entered is not within range. Please enter a number between 30-120: 35
"35" is a valid number.
Please enter number of sentences per paragraph, between 3-8: <empty>
Sorry, you did not enter anything. Please enter a number between 3-8: 2
The number entered is not within range. Please enter a number between 3-8: 9
The number entered is not within range. Please enter a number between 3-8: 5
"5" is a valid number.

The great events on which
my resignation depended having at length taken place; I have now the honor of offering my sincere Congratulations to Congress and of presenting myself before them to surrender into their hands the trust committed to me, and to claim the indulgence of retiring from the Service of my Country. Happy in the confirmation of our Independence and Sovereignty, and pleased with the opportunity afforded the United States of becoming a respectable Nation, I resign with satisfaction the Appointment I accepted with diffidence. A diffidence in my abilities to accomplish so arduous a task, which however was superseded by a confidence in the

Space race

<empty>

rectitude of our Cause, the support of the Supreme Power of the Union, and the patronage of Heaven. The Successful termination of the War has verified the most sanguine expectations, and my gratitude for the interposition of Providence, and the assistance I have received from my Country-men, encreases with every review of the momentous Contest. While I repeat my obligations to the Army in general, I should do injustice to my own feelings not to acknowledge in this place the peculiar Services and distinguished merits of the Gentlemen who have been attached to my person during the War.

It was impossible the choice of confidential Officers to compose my family should have been more fortunate. Permit me Sir, to recommend in particular those, who have continued in Service to the present moment, as worthy of the favorable notice and patronage of Congress I consider it an indispensable duty to close this last solemn act of my Official life, by commending the Interests of our dearest Country to the protection of Almighty God, and those who have the superintendence of them, to his holy keeping. Having now finished the work assigned me, I retire from the great theatre of Action; and bidding an Affectionate farewell to this August body under whose orders I have so long acted, I here offer my Commission, and take my leave of all the employments of public life.

---George Washington

Is there another piece of text to format? (yes/no) <empty>
You did not enter anything. Would you like to format more text? (yes/no) That is not yes or no. Is there another piece of text to format? (yes/no)

Please select a speech to format. Choices are Gettysburg, Washington, or Lou: Lou"Lou" is in my memory.
Please enter number of indents per first line, between 0-2: 2
"2" is a valid number.

Please enter number of characters allowed per line, between 30-120: 70"70" is a valid number.

asdfasf

yes

Please enter number of sentences per paragraph, between 3-8: 3 "3" is a valid number.

Fans, for the past two weeks you have been reading about the bad break I got. Yet today I consider myself the luckiest man on the face of this earth. I have been in ballparks for 17 years and have never received anything but kindness and encouragement from you fans.

Look at these grand men. Which of you wouldn’t consider it the highlight of his career just to associate with them for even one day? Sure, I’m lucky.

Who wouldn’t consider it an honor to have known Jacob Ruppert? Also, the builder of baseball’s greatest empire, Ed Barrow? To have spent six years with that wonderful little fellow, Miller Huggins?

Then to have spent the next nine years with that outstanding leader, that smart student of psychology, the best manager in baseball today, Joe McCarthy? Sure, I’m lucky. When the New York Giants, a team you would give your right arm to beat, and vice versa, sends you a gift — that’s something.

When everybody down to the groundskeepers and those boys in white coats remember you with trophies - that’s something. When you have a wonderful mother-in-law who takes sides with you in squabbles with her own daughter - that’s something. When you have a father and a mother who work all their lives so you can have an education and build your body - it’s a blessing.

When you have a wife who has been a tower of strength and shown more courage than you dreamed existed — that’s the finest I know. So I close in saying that I may have had a tough break, but I have an awful lot to live for.
---Lou Gehrig

Is there another piece of text to format? (yes/no) noThank you. Good bye

Solutions

Expert Solution

Hi, Please find the solution and rate the answer: Thanks

import java.util.Scanner;

class Scratch {
    static String speech1 = "Fourscore and seven years ago our fathers brought forth, on this continent, a new nation, conceived in liberty, and dedicated to the proposition that all men are created equal. Now we are engaged in a great civil war, testing whether that nation, or any nation so conceived, and so dedicated, can long endure. We are met on a great battle-field of that war. We have come to dedicate a portion of that field, as a final resting-place for those who here gave their lives, that that nation might live.\n" +
            "\n" +
            "It is altogether fitting and proper that we should do this. But, in a larger sense, we cannot dedicate, we cannot consecrate—we cannot hallow—this ground. The brave men, living and dead, who struggled here, have consecrated it far above our poor power to add or detract. The world will little note, nor long remember what we say here, but it can never forget what they did here.\n" +
            "\n" +
            "It is for us the living, rather, to be dedicated here to the unfinished work which they\n" +
            "\n" +
            "who fought here have thus far so nobly advanced. It is rather for us to be here dedicated to the great task remaining before us—that from these honored dead we take increased devotion to that cause for which they here gave the last full measure of devotion—that we here highly resolve that these dead shall not have died in vain—that this nation, under God, shall have a new birth of freedom, and that government of the people, by the people, for the people, shall not perish from the earth.";
    static String speech2 = "The great events on which\n" +
            "my resignation depended having at length taken place; I have now the honor of offering my sincere Congratulations to Congress and of presenting myself before them to surrender into their hands the trust committed to me, and to claim the indulgence of retiring from the Service of my Country. Happy in the confirmation of our Independence and Sovereignty, and pleased with the opportunity afforded the United States of becoming a respectable Nation, I resign with satisfaction the Appointment I accepted with diffidence. A diffidence in my abilities to accomplish so arduous a task, which however was superseded by a confidence in the\n" +
            "\n" +
            "Space race\n" +
            "\n" +
            "<empty>\n" +
            "\n" +
            "rectitude of our Cause, the support of the Supreme Power of the Union, and the patronage of Heaven. The Successful termination of the War has verified the most sanguine expectations, and my gratitude for the interposition of Providence, and the assistance I have received from my Country-men, encreases with every review of the momentous Contest. While I repeat my obligations to the Army in general, I should do injustice to my own feelings not to acknowledge in this place the peculiar Services and distinguished merits of the Gentlemen who have been attached to my person during the War.\n" +
            "\n" +
            "It was impossible the choice of confidential Officers to compose my family should have been more fortunate. Permit me Sir, to recommend in particular those, who have continued in Service to the present moment, as worthy of the favorable notice and patronage of Congress I consider it an indispensable duty to close this last solemn act of my Official life, by commending the Interests of our dearest Country to the protection of Almighty God, and those who have the superintendence of them, to his holy keeping. Having now finished the work assigned me, I retire from the great theatre of Action; and bidding an Affectionate farewell to this August body under whose orders I have so long acted, I here offer my Commission, and take my leave of all the employments of public life.\n" +
            "\n" +
            "---George Washington";
    static String speech3 = "Fans, for the past two weeks you have been reading about the bad break I got. Yet today I consider myself the luckiest man on the face of this earth. I have been in ballparks for 17 years and have never received anything but kindness and encouragement from you fans.\n" +
            "\n" +
            "Look at these grand men. Which of you wouldn’t consider it the highlight of his career just to associate with them for even one day? Sure, I’m lucky.\n" +
            "\n" +
            "Who wouldn’t consider it an honor to have known Jacob Ruppert? Also, the builder of baseball’s greatest empire, Ed Barrow? To have spent six years with that wonderful little fellow, Miller Huggins?\n" +
            "\n" +
            "Then to have spent the next nine years with that outstanding leader, that smart student of psychology, the best manager in baseball today, Joe McCarthy? Sure, I’m lucky. When the New York Giants, a team you would give your right arm to beat, and vice versa, sends you a gift — that’s something.\n" +
            "\n" +
            "When everybody down to the groundskeepers and those boys in white coats remember you with trophies - that’s something. When you have a wonderful mother-in-law who takes sides with you in squabbles with her own daughter - that’s something. When you have a father and a mother who work all their lives so you can have an education and build your body - it’s a blessing.\n" +
            "\n" +
            "When you have a wife who has been a tower of strength and shown more courage than you dreamed existed — that’s the finest I know. So I close in saying that I may have had a tough break, but I have an awful lot to live for.\n" +
            "---Lou Gehrig";

    public static void main(String[] args) {
        boolean loop = false;
        Scanner sc = new Scanner(System.in);
        do {
            System.out.println("Please select a speech to format. Choices are Gettysburg, Washington, or Lou:");
            String line = sc.nextLine();
            String paraPrintChoice = "";
            while (line.trim().length() == 0 && !(line.equalsIgnoreCase("Gettysburg") ||line.equalsIgnoreCase("Washington")|| line.equalsIgnoreCase("LOU"))) {
                System.out.println("Sorry, that is not in my memory. Your choices are Gettysburg, Washington, or Lou:" +
                        "You did not enter anything. Your choices are Gettysburg, Washington, or Lou:");
                line = sc.nextLine();
            }
            while(!(line.equalsIgnoreCase("gettysburg")||line.equalsIgnoreCase("Lou")|| line.equalsIgnoreCase("washington"))){
                System.out.println(line +" is not in my memory:try again");
                line = sc.nextLine();
            }
            if (line.equalsIgnoreCase("gettysburg")) {
                paraPrintChoice = speech1;
                System.out.println(line + " is in my memory");
            }

            else if (line.equalsIgnoreCase("Washington")) {
                paraPrintChoice = speech2;
                System.out.println(line + " is in my memory");
            }

            else if (line.equalsIgnoreCase("LOU")) {
                paraPrintChoice = speech3;
                System.out.println(line + " is in my memory");
            }

            System.out.println("Please enter number of indents per first line, between 0-2:");
            int indentsChoice = sc.nextInt();
            while (indentsChoice < 0 || indentsChoice > 2) {
                System.out.println("The number entered is not within range. Please enter a number between 0-2:");
                indentsChoice = sc.nextInt();
            }

            System.out.println(indentsChoice + " is a valid number");
            System.out.println();
            System.out.println("Please enter number of characters allowed per line, between 30-120:");
            int allowedCharsPerline = sc.nextInt();
            while (allowedCharsPerline < 30 || allowedCharsPerline > 120) {
                System.out.println("The number entered is not within range. Please enter a number between 30-120:");
                allowedCharsPerline = sc.nextInt();
            }

            System.out.println(allowedCharsPerline + " is a valid number");
            System.out.println("Please enter number of sentences per paragraph, between 3-8:");
            int allowedSentencesPerPara = sc.nextInt();
            while (allowedSentencesPerPara < 3 || allowedSentencesPerPara > 8) {
                System.out.println("The number entered is not within range. Please enter a number between 3-8:");
                allowedSentencesPerPara = sc.nextInt();
            }

            System.out.println(allowedSentencesPerPara + " is a valid number");
            paraPrintChoice = paraPrintChoice.replace("\n", " ");//Please check if this is required;

            int noOflinesPrinted = 0, noOfcharsPrinted = 0, noOfparasPrinted = 0;

            for (char ch : paraPrintChoice.toCharArray()) {
                System.out.print(ch);
                noOfcharsPrinted++;
                if (noOfcharsPrinted == allowedCharsPerline) {
                    System.out.println();
                    noOfcharsPrinted=0;
                    noOflinesPrinted++;
                }
                if (noOflinesPrinted == allowedSentencesPerPara) {
                    System.out.println();
                    noOflinesPrinted = 0;
                    for (int i = 0; i < indentsChoice; i++) {
                        System.out.print("\t");
                    }
                }

            }
            System.out.println("Is there another piece of text to format? (yes/no) yes");
            String temp = sc.nextLine();
            while(temp.trim().equalsIgnoreCase("")){
                System.out.println("You did not enter anything. Would you like to format more text? (yes/no) That is not yes or no. Is there another piece of text to format? (yes/no)");
                temp=sc.nextLine();
            }
            if(temp.equalsIgnoreCase("no")){
                loop=false;
            }
        }while(loop);
        System.out.println("good bye");
    }
}

Sample Out:


Related Solutions

CompSci 251: Assignment 3 Due 2/20, 2017 10:00am Topics Covered: Instance variables and methods; using a...
CompSci 251: Assignment 3 Due 2/20, 2017 10:00am Topics Covered: Instance variables and methods; using a driver class 1 Introduction This assignment will have you implement your first real Java class using instance variables(state) and meth- ods(behaviour). It will also probably be the first time that you write a program with a driver class. 2 Income tax computation Most Americans (not just Americans, really!) complain about filing their income taxes. Some people dont think they should pay at all. Others...
CS 238 – Assembly Language Programming Fall 2019 Assignment 1 (Due: September 10, 2019) Submission Instructions:...
CS 238 – Assembly Language Programming Fall 2019 Assignment 1 (Due: September 10, 2019) Submission Instructions: Online submissions on Blackboard are preferred. Feel free to edit this Word document to insert your answers. Multiple online submissions on Blackboard are allowed, but only the last online submission made by the midnight of September 10 will be graded. Alternatively, a paper submission is possible, but it needs to be done in class on September 10. 1. Data can be interpreted as required...
ASSIGNMENT 1 · ECON 3060 - 01 Due Date: September 4, 2019 1) The Graduate Management...
ASSIGNMENT 1 · ECON 3060 - 01 Due Date: September 4, 2019 1) The Graduate Management Admission Test (GMAT) is a standardized test used by schools to determine the aptitude of individuals who are applying for MBA programs. The range of the GMAT score is 200-800. Brian has recently taken the exam and scored 720. This is an example of _______ data. A) nominal B) ordinal C) interval D) ratio 2) A respondent of a survey indicates that she is...
HOMEWORK ASSIGNMENT # 1 Due Date: Tuesday, February 20, 2018 by 5:15 pm Required format: This...
HOMEWORK ASSIGNMENT # 1 Due Date: Tuesday, February 20, 2018 by 5:15 pm Required format: This assignment is worth 20 pts. You should use Microsoft Word or a similar typing program to write your answers to the questions below. Hand-written copies will be subject to a deduction of 5 pts. Take a photo of your graphs and paste them as a picture in your document or draw them using one of the drawing tools available in Excel or Word. All...
Assignment 2: Create a form that collects 5 different pieces of data. Once the user clicks...
Assignment 2: Create a form that collects 5 different pieces of data. Once the user clicks the submit button, the processing PHP file displays the data that was entered thru the form, performs a calculation, and displays the result. To receive full credit, students need to implement the following: Create variables with valid names and assign values to them Use literals and concatenate strings Use $_POST Use echo statements to display data on a page Code string and numeric expressions...
CSE/EEE 230 Assignment 4 Fall 2019 Due Sept 30 (11:59PM) In this assignment, you are to...
CSE/EEE 230 Assignment 4 Fall 2019 Due Sept 30 (11:59PM) In this assignment, you are to complete a MIPS program so it will perform the required tasks. The main function of the code is provided. Do not change the code in the main function. There is a loop in the main function. You are to complete the program by writing two functions. Pay particular attention to the purpose of each function and how the parameters and return value are to...
C++ Assignment Hi, I need to create a program that: 1.Reads a source file (.txt) with...
C++ Assignment Hi, I need to create a program that: 1.Reads a source file (.txt) with following information: 1,2,3,4,5 red,blue,green,yellow,orange left, right,front, back 2. After having program read the .txt file, output the above information in categories of Symbol, Token Type, and Count : Example: Symbol---Token Type (data type)----Count (how many times symbol appeared in .txt file) =========================================================================== 1 ----digit ----1 2 ----digit ----1 red ----color ----1 blue ----color ----1 left ----direction ----1 right ----direction    ----1
C++ Assignment Hi, I need to create a program that: 1.Reads a source file (.txt) with...
C++ Assignment Hi, I need to create a program that: 1.Reads a source file (.txt) with following information: 1,2,3,4,5 red,blue,green,yellow,orange left, right,front, back 2. After having program read the .txt file, output the above information in categories of Symbol, Token Type, and Count : Example: Symbol---Token Type (data type)----Count (how many times symbol appeared in .txt file) =========================================================================== 1 ----digit ----1 2 ----digit ----1 red ----color ----1 blue ----color ----1 left ----direction ----1 right ----direction    ----1
C++ Assignment Hi, I need to create a program that: 1.Reads a source file (.txt) with...
C++ Assignment Hi, I need to create a program that: 1.Reads a source file (.txt) with following information: 1,2,3,4,5 red,blue,green,yellow,orange left, right,front, back 2. After having program read the .txt file, output the above information in categories of Symbol, Token Type, and Count : Example: Symbol---Token Type (data type)----Count (how many times symbol appeared in .txt file) =========================================================================== 1 ----digit ----1 2 ----digit ----1 red ----color ----1 blue ----color ----1 left ----direction ----1 right ----direction    ----1
Java program. Need to create a class names gradesgraph which will represent the GradesGraphtest program. Assignment...
Java program. Need to create a class names gradesgraph which will represent the GradesGraphtest program. Assignment Create a class GradesGraph that represents a grade distribution for a given course. Write methods to perform the following tasks: • Set the number of each of the letter grades A, B, C, D, and F. • Read the number of each of the letter grades A, B, C, D, and F. • Return the total number of grades. • Return the percentage of...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT