Question

In: Computer Science

DESCRIPTION Objectives To develop a recursive solution to an open-ended iterative problem To develop a program...

DESCRIPTION
Objectives

To develop a recursive solution to an open-ended iterative problem
To develop a program that manages bad input
Description

Write a program (printSquares.scala) that read non-negative Int values from a user one at a time. For each positive Int, print out a message with the square of the number. Your program should quit when the use enters a negative Int. Note: You will also need to manage bad input! If the user types something in that isn't an Int, your program should print an error message and ask again! Pay close attention to the specific messages that your program must print!

Remember: You don't want any side effects with recursion, so you should not use any "global" variables in your program!

Sample Run 1

$ scala printSquares.scala
Enter an Int (negative to quit):
>4
4^2 is 16.
Enter an Int (negative to quit):
>2
2^2 is 4.
Enter an Int (negative to quit):
>-3
Goodbye!
Sample Run 2

$scala printSquares.scala
Enter an Int (negative to quit):
>5
5^2 is 25.
Enter an Int (negative to quit):
>3
3^2 is 9.
Enter an Int (negative to quit):
>six
That is not an Int!
Enter an Int (negative to quit):
>6.0
That is not an Int!
Enter an Int (negative to quit):
>6
6^2 is 36.
Enter an Int (negative to quit):
>-3
Goodbye!
Hints

Write 2 recursive functions. One to ask the user for an Int and recurse until a Int is entered, and one to call the first function to get an Int, and print the square (ending if the Int is negative).
Use try/catch blocks to trap run time exceptions like NumberFormatException

Solutions

Expert Solution

We will follow the instructions as specified in the problem statement.

Let's see the flow of the program we have written:

1. We will create an object with the name printSquares and enclose all of our code into it.

2. We will define the main function from which we will call our function getOutput (). This will be a recursive function that will call our takeInput() function and will end if the user entered a negative integer, otherwise, it will print the square of the number entered. (According to the problem statement, this will be the second recursive function, "one to call the first function to get an Int, and print the square") This function will make a recursive call to itself at the end, in order to repeat the process.

3. The takeInput() function will prompt the user for an integer by displaying a message, store that message in a val and return it to the getOutput() function, which will print its square, if it is found to be non-negative, otherwise, it will print "Goodbye!".

4. Please note that we are taking input from the user using scala.io.StdIn.readInt ().

5. Please note that in takeInput() a NumberFormatException will be raised if the user did not enter an integer when prompted for it. Therefore, we are using try block around the statement where the user is asked for the input and in the corresponding catch block, we will display the message that the value entered wasn't an integer and we will recursively call the takeInput() function.

Please find all the code explanations within the code itself as comments.

Here is the full code:



object printSquares {

        // main function 
        def main (args: Array[String]) {
                // call the getOutput() function to initiate the process
                getOutput();
        }

        // this function will take the user input and
        // find and print its square if the input 
        // was a non-negative integer, otherwise, 
        // will print Goodbye and end
        def getOutput () {
                        
                // call the takeInput () function to 
                // get the input from the user
                val num = takeInput ();

                // check if input is negative
                if (num < 0) {
                        // if yes, print GoodBye
                        println ("Goodbye!");
                        // and return
                        return;
                }

                // otherwise, if it's non-negative
                
                // find its square
                val square = num * num;
                // print the square
                println (num + "^2 is " + square + ".");

                // recursively call getOutput () to repeat the process
                getOutput ();
        }

        // this function will take the input and 
        // return it(the integer) to the getOutput () function
        def takeInput () : Int = {
                        
                // prompt the user for the integer
                println ("Enter an Int(negative to quit):");

                try {
                        // use the readInt() function to take the input
                        val num = scala.io.StdIn.readInt();     

                        // return the integer to getOutput ()
                        return num
                } catch {
                        // if user did not enter an integer, an Exception
                        // will be thrown, and we will display the message to the user
                        case e: NumberFormatException => println("That is not an Int!");

                        // as the input couldn't be found, we will call the takeInput() again
                        val input = takeInput ();

                        // return the found input
                        return input;
                }
        }
}

Please refer to the screenshots of the code for understanding the indentation.

the main() function and the getOutput() function

the takeInput() function

The full code screenshot:

Let's look at the input-output as given in the problem statement:

Input-Output 1:

Input-Output 2:


Related Solutions

Objectives To develop a recursive solution that reurns a tuple To develop a program that manages...
Objectives To develop a recursive solution that reurns a tuple To develop a program that manages bad input Description Write a program (sumAndCount.scala) that uses a recursive function that reads Int values from a user one at a time until the user types in the word "quit" (case insensitive!). Your function should return a tuple containing 2 Int values. The first should be the sum of all the Ints, and the second should be the number of Ints entered. Your...
Write two Java programs ( Iterative and Recursive programs ) that solves Tower of Hanoi problem?use...
Write two Java programs ( Iterative and Recursive programs ) that solves Tower of Hanoi problem?use 4 disks and 3 bars
Description of the problem: 1. Construct the recursive diagram of the Remove function that invokes the...
Description of the problem: 1. Construct the recursive diagram of the Remove function that invokes the function recursive getIndexOf using the main program described in your module. 2. Construct the recursive diagram of the getFrequencyOf function that invokes the function recursive countFrequency using the main program described in your module. C++ Code of getIndex and getFrequency template void ArrayBag::display() const{ cout int ArrayBag::getFrequencyOf(const ItemType& anEntry) const { return countFrequency(anEntry, 0); } // end getFrequencyOf template int ArrayBag::countFrequency(const ItemType& target,int sear...
Program this in C thank you PROBLEM DESCRIPTION: Write a program to implement the following requirement:...
Program this in C thank you PROBLEM DESCRIPTION: Write a program to implement the following requirement: The program will read from standard input two things - a string str1 on the first line of stdin (this string may be an empty string) - a string str2 on the second line of stdin (this string may be an empty string) Note that stdin does not end with '\n'. The program will output a string that is the concatenation of string str1...
Using the four step (viz., analyze the problem, develop a solution, code the solution, test the...
Using the four step (viz., analyze the problem, develop a solution, code the solution, test the program) program development method, write a C++ program that permits users to enter the following information about your small company’s 5 employees and then writes the information to a file “employee.txt”: ID No. Sex (M/F) Hourly Wage Years with the Company Make sure that you open the file for write using the two-step process of “trial read followed by write” so that an existing...
show some example of few recursive problem in java language and the solution code. Need more...
show some example of few recursive problem in java language and the solution code. Need more practice as a new learner
Problem 1: Recursive anagram finder please used Java please Write a program that will take a...
Problem 1: Recursive anagram finder please used Java please Write a program that will take a word and print out every combination of letters in that word. For example, "sam" would print out sam, sma, asm, ams, mas, msa (the ordering doesn't matter) input: cram output: cram crma carm camr cmra cmar rcam rcma racm ramc rmca rmac acrm acmr arcm armc amcr amrc mcra mcar mrca mrac macr marc Hints: Your recursive function should have no return value and...
Standardized Open-ended assessment (ex. Essay) requiring students to develop their own answers Assessment following instruction to...
Standardized Open-ended assessment (ex. Essay) requiring students to develop their own answers Assessment following instruction to judge performance Evaluation tool charting criteria and levels of performance Evaluation tool resulting in a numerical score Assessment comparing performance to an average standard level of performance derived from a group Assessment administered with standard directions to many schools, groups, and individuals Assessment designed to measure mastery of specific criteria Evaluation of students' answer choices to individual test questions Assessment requiring students to select...
Develop a Java program for this problem where the user inputs an Earth age and the...
Develop a Java program for this problem where the user inputs an Earth age and the program will then display the age on Mercury, Venus, Jupiter, and Saturn. The values for d are listed in the table. Planet d = Approximate Number of Earth Days for This Planet to Travel Around the Sun Mercury 88 Venus 225 Jupiter 4380 Saturn 10767
Your client, Anthony, just learned that his mother has terminal cancer. Develop 3 open ended questions...
Your client, Anthony, just learned that his mother has terminal cancer. Develop 3 open ended questions and 3 closed questions to help Anthony process this news. Additionally, provide an example of 1 open ended question and 1 closed question that you would not ask Anthony.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT