Question

CAN SOMEONE HELP WITH THIS? Part 1: power() method We want to write a method that...

CAN SOMEONE HELP WITH THIS?

Part 1: power() method

We want to write a method that will enable us to calculate a number to a given power. In other words, we are writing a method to mimic what the Math.pow() method we have seen before does.

To write this method use the following requirements:

  1. The method should return an integer.
  2. It should have two parameters x and y both integers.
  3. The name of this method will be power().
  4. For the sake of being able to use the method without creating an object, the method must be a static method.

Task 1: Develop the logic and write an outline for the power() method

Before you begin coding, make sure that you understand logically how to produce the desired result. You can use an algorithm, flowchart or pseudocode for doing this. Once you think you have the solution then proceed to write out the outline (in code/pseudocode) below.

You cannot use the Math.pow() method to generate your result. Your method must take x and y as parameters and return the value xy.

Deliverable 1: Write the outline (in code/pseudocode[1]) of the power() method below. You must include the method’s name, the parameters (including their types) and the return type in the outline.

Task 2: Write the code

Before you write the code, make sure that you have a set of test cases so you can use that to check your program. Use the table below to develop at least 5 test cases that you will use to check the correctness of your program.

Deliverable 2: Fill up the table below with >=5 test cases.

Case #

x

y

Expected result

Observed result

1

2

3

4

5

6

7

8

9

Next, write your program. Make sure that the method you are writing is before where the main() method begins. Also, make sure that you are calling the power() method appropriately and that you are displaying the result.

Deliverable 3: Fill up the observed results column in your test cases table. If there is any discrepancy between expected and observed results then troubleshoot and fix your code.

Deliverable 4: Include your source code below.

Part 2: search() method

In this part you will develop a method that takes 2 parameters: the first parameter is a String, and the second parameter is a single character. The objective of the method is to return the number of times the character appears in that string.

                Ex: search(“bobby”, ‘b’) – this should return a value of 3 because the character ‘b’ appears 3 times in the string “bobby.”

Your method should also be able to count both lowercase and uppercase versions of the same character.

                Thus, search(“Bobby”, ‘b’) – this should also return a value of 3 and not 2.

Task 3: Develop the logic and write an outline for the search() method

Before you begin coding, make sure that you understand logically how to produce the desired result. You can use an algorithm, flowchart or pseudocode for doing this. Once you think you have the solution then proceed to write out the outline (in code/pseudocode) below.

You can use any of the standard String functions you have learned before to search the String to figure out if and where the character appears in the String (ex: the indexOf() method), or you can scan through the String and count the instances.

Deliverable 5: Write the outline (in code/pseudocode) of the search() method below. You must include the method’s name, the parameters (including their types) and the return type in the outline.

Task 4: Write the code

Next, write your program. Make sure that the method you are writing is before where the main() method begins. Also, make sure that you are calling the search() method appropriately and that you are displaying the result.

Deliverable 6: Include your source code below.

Task 5: (Extra Credit) Recursive power() method

The power() method above takes 2 parameters x and y. How would you write a recursive version of the power() method.

Write a recursive power() method.

Assume that the power() method only takes int parameters and returns an int parameter.

Make sure that you identify the base case and the recursive case.

[Hint: the variable that is being recursed on is y. Base case is when y=0, you return 1.]

Deliverable 7: Show the output of your code below. Include your source code below that.

[1] Psuedocode is the term we use for writing program descriptions in code-like language but not specific language code. See samples here: https://users.csc.calpoly.edu/~jdalbey/SWE/pdl_std.html

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

Here are the pseudocodes for all three methods (in simple language).

power(x, y):

Initialize result to 1

loop for y times:

              multiply result with x and store in result

return result

powerRecursive(x, y): (recursive version of above method)

if y is 0: return 1

else: return x * powerRecursive(x,y-1)

search(str, c):

convert str to lower case

convert c to lower case

initialize count to 0

loop through each character in str:

              if current character is c:

                           increment count

return count

Here is the completed source code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks

Note: the table displaying test cases and results for power method are shown in the output, please refer to that.

// Test.java

public class Test {

              /**

              * method to find the value of x^y

              *

              * @param x

              *            integer

              * @param y

              *            exponent value, should be >=0

              * @return x^y

              */

              public static int power(int x, int y) {

                           // defining a variable to 1

                           int result = 1;

                           // looping and multiplying result with x, y times

                           for (int i = 0; i < y; i++) {

                                         result = result * x;

                           }

                           return result;

              }

              // recursive version of the above method

              public static int powerRecursive(int x, int y) {

                           if (y <= 0) {

                                         // base condition

                                         return 1;

                           }

                           // multiplying x with the value returned by powerRecursive(x, y - 1) and

                           // returning it

                           return x * powerRecursive(x, y - 1);

              }

              /**

              * method to count the number of times a character occurring in a String

              *

              * @param str

              *            target string

              * @param c

              *            character to be searched

              * @return the count of c in str

              */

              public static int search(String str, char c) {

                           // converting str and c to lower case to minimize comparisons

                           str = str.toLowerCase();

                           c = Character.toLowerCase(c);

                           //initializing count to 0

                           int count = 0;

                           //looping through each character in str

                           for (int i = 0; i < str.length(); i++) {

                                         //checking if current character is c

                                         if (str.charAt(i) == c) {

                                                       //incrementing count

                                                       count++;

                                         }

                           }

                           //returning count

                           return count;

              }

              public static void main(String[] args) {

                           // testing all methods

                           System.out.println("Testing power() iterative");

                           System.out.println("power(0,1) - Expected: " + (int) Math.pow(0, 1)

                                                       + ", Observed: " + power(0, 1));

                           System.out.println("power(5,1) - Expected: " + (int) Math.pow(5, 1)

                                                       + ", Observed: " + power(5, 1));

                           System.out.println("power(5,5) - Expected: " + (int) Math.pow(5, 5)

                                                       + ", Observed: " + power(5, 5));

                           System.out.println("power(-5,1) - Expected: " + (int) Math.pow(-5, 1)

                                                       + ", Observed: " + power(-5, 1));

                           System.out.println("power(-5,2) - Expected: " + (int) Math.pow(-5, 2)

                                                       + ", Observed: " + power(-5, 2));

                           System.out.println("\nTesting power() recursive");

                           System.out.println("power(0,1) - Expected: " + (int) Math.pow(0, 1)

                                                       + ", Observed: " + powerRecursive(0, 1));

                           System.out.println("power(5,1) - Expected: " + (int) Math.pow(5, 1)

                                                       + ", Observed: " + powerRecursive(5, 1));

                           System.out.println("power(5,5) - Expected: " + (int) Math.pow(5, 5)

                                                       + ", Observed: " + powerRecursive(5, 5));

                           System.out.println("power(-5,1) - Expected: " + (int) Math.pow(-5, 1)

                                                       + ", Observed: " + powerRecursive(-5, 1));

                           System.out.println("power(-5,2) - Expected: " + (int) Math.pow(-5, 2)

                                                       + ", Observed: " + powerRecursive(-5, 2));

                          

                           System.out.println("\nTesting search() method");

                           System.out.println("search(\"Bobby\",'b') - Expected: 3, Observed: "

                                                       + search("Bobby", 'b'));

                           System.out.println("search(\"Bobby\",'o') - Expected: 1, Observed: "

                                                       + search("Bobby", 'o'));

                           System.out.println("search(\"Java\",'z') - Expected: 0, Observed: "

                                                       + search("Java", 'z'));

              }

}

/*OUTPUT*/

Testing power() iterative

power(0,1) - Expected: 0, Observed: 0

power(5,1) - Expected: 5, Observed: 5

power(5,5) - Expected: 3125, Observed: 3125

power(-5,1) - Expected: -5, Observed: -5

power(-5,2) - Expected: 25, Observed: 25

Testing power() recursive

power(0,1) - Expected: 0, Observed: 0

power(5,1) - Expected: 5, Observed: 5

power(5,5) - Expected: 3125, Observed: 3125

power(-5,1) - Expected: -5, Observed: -5

power(-5,2) - Expected: 25, Observed: 25

Testing search() method

search("Bobby",'b') - Expected: 3, Observed: 3

search("Bobby",'o') - Expected: 1, Observed: 1

search("Java",'z') - Expected: 0, Observed: 0

Add a comment
Know the answer?
Add Answer to:
CAN SOMEONE HELP WITH THIS? Part 1: power() method We want to write a method that...
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
  • Write a recursive method that counts the number of vowels in a string. It must return...

    Write a recursive method that counts the number of vowels in a string. It must return the number of vowels. Use appropriate parameters as needed. Hint: There's an ArrayList method called contains that might make checking whether a character is a vowel easier.

  • LAB PROMPT: Lab 06 For this lab you are going to practice writing method signatures, implementing...

    LAB PROMPT: Lab 06 For this lab you are going to practice writing method signatures, implementing if statements, and improve your skills with for loops. The methods you will be writing have nothing to do with each other but allow you to use the skills you have gained so far to solve a series of small problems. Power For this method you will practice using methods from the Math class. The first step you must take is to write the...

  • Using Java: 1. Recursive Multiplication Write a recursive function that accepts two arguments into the parameters...

    Using Java: 1. Recursive Multiplication Write a recursive function that accepts two arguments into the parameters x and y. The function should return the value of x times y. Remember, multiplication can be performed as repeated addition as follows: 5×6=6+6+6+6+6 2. Recursive findings Write a recursive boolean method named reFinding. The method should search an array for a specified value, and return true if the value is found in the array, or false if the value is not found in...

  • **WRITE IN C# INTERMEDIATE LEVEL CODE A 2ND SEMESTER STUDENT COULD UNDERSTAND WELL** Problem Statement: Write...

    **WRITE IN C# INTERMEDIATE LEVEL CODE A 2ND SEMESTER STUDENT COULD UNDERSTAND WELL** Problem Statement: Write an abstract class called Vacation includes a budget and a destination. It has an abstract method returning by how much the vacation is over or under budget. This class has two non-abstract subclasses: All-Inclusive Vacation brand (such as ClubMed, Delta Vacations, etc) a rating (you can use # of stars) price Piecemeal Vacation set of items (hotel, meal, airfare, etc) set of corresponding costs...

  • write a java program :- Use a recursive method that can take an arbitrarily long string...

    write a java program :- Use a recursive method that can take an arbitrarily long string and reverse the order of its characters. Example: "Real men don't eat quiche." would be ".ehciuq tea t'nod nem leaR" must use RECURSION to solve this challenge. make sure to comment the code thoroughly.

  • Assignment Overview In Part 1 of this assignment, you will write a main program and several...

    Assignment Overview In Part 1 of this assignment, you will write a main program and several classes to create and print a small database of baseball player data. The assignment has been split into two parts to encourage you to code your program in an incremental fashion, a technique that will be increasingly important as the semester goes on. Purpose This assignment reviews object-oriented programming concepts such as classes, methods, constructors, accessor methods, and access modifiers. It makes use of...

  • Write a static method called encodeString that takes a string as input and prints to the...

    Write a static method called encodeString that takes a string as input and prints to the console a word where each letter is advanced by one value. In addition, your method should return the encoded String. You may make use of the method provided below to help you. public static char encode(char x) { int current = x; current++; return (char)current; } This method takes a character and returns an "encoded" character. In other words, encode('a') will return 'b'. Your...

  • JAVA PROJECT Part 1 - Normalize Text The first thing we will do is normalize the...

    JAVA PROJECT Part 1 - Normalize Text The first thing we will do is normalize the input message so that it’s easier to work with. Write a method called normalizeText which does the following: Removes all the spaces from your text Remove any punctuation (. , : ; ’ ” ! ? ( ) ) Turn all lower-case letters into upper-case letters Return the result. The call normalizeText(“This is some \“really\” great. (Text)!?”) should return “THISISSOMEREALLYGREATTEXT” Part 2 - Obfuscation...

  • I need java code for the following problem. Lab 7: Methods 1. Write a Java program called Numbers that calls the following methods and displays the returned value: Write a method called cubelt that a...

    I need java code for the following problem. Lab 7: Methods 1. Write a Java program called Numbers that calls the following methods and displays the returned value: Write a method called cubelt that accepts one integer parameter and returns the value raised to the third power as an integer. o Write a method called randominRange that accepts two integer parameters representing a range. The method returns a random integer in the specified range inclusive. 2. o Write a method...

  • ​​​​​​public static int countCharacter(String str, char c) { // This recursive method takes a String and...

    ​​​​​​public static int countCharacter(String str, char c) { // This recursive method takes a String and a char as parameters and // returns the number of times the char appears in the String. You may // use the function charAt(int i) described below to test if a single // character of the input String matches the input char. // For example, countCharacter(“bobbie”, ‘b’) would return back 3, while // countCharacter(“xyzzy”, ‘y’) would return back 2. // Must be a RECURSIVE...

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