Labs
- Write a program with a method that calculates a power — a base number raised to the power of an exponent. The method should take two parameters: a double (the base) and an int (the exponent). The method should return a double: the base raised to the power of the exponent. In the
mainmethod, prompt the user to enter the base and the exponent; use the method to perform the calculation; then print the result returned by the method. (Do not useMath.pow(double, double)in your solution.)
(Solution: PowerMethod.java)
-
We will be writing several methods in one class.
-
Write a method named
calculateTriangleto calculate the "nth triangle" for a givenn. The triangle of a numbernis1 + 2 + ... + n. For example, calculating the triangle of5is1 + 2 + 3 + 4 + 5and the result is15. The method will take an integer and return an integer. (Do not use the formulan * (n + 1) / 2in your solution.) - Write a method named
getNumberthat prompts the use to enter a number. It will take no parameters, but will prompt the user to enter a number. The method will return the integer the user entered. -
Call
getNumberand yourcalculateTrianglemethod from (1) inmain. Print the returned number. Now test your program. Themainmethod below may help with the organization of your class.public static void main(String[] args) { //Call the method to get user data //Use the data to get triangle //Output the triangle }(Solution: TriangleCalc.java)
-
Write another method named
calculateTriangleStringto return aStringrepresenting the addition for an nth triangle. For example, for the input5, the method would return1 + 2 + 3 + 4 + 5. Call the method frommainafter you output the triangle of a number. Test your program.(Solution: TriangleCalcString.java)
-
We will write overloaded test methods in our class from (2) to test triangle calculation.
-
Write a method called
testEquals, which returns aboolean. The method will have twointparameters. The first parameter is the expected value. The second is a test value. If the two values are equal, printPassedand returntrue. If they are not equal, printFailed: expected X but was Y(whereXandYare the actual values of the parameters) and returnfalse. -
Comment out all code in
main. Call yourcalculateTrianglemethod inmain, and use the returned value in a call totestEquals. Do this method call with several values, and make sure you do so with a value that would causetestEqualsto fail.(Solution: TriangleCalcTest.java)
-
Write a
testEqualsmethod with twoStringparameters. Use it to test the output of yourcalculateTriangleStringRemember to use.equals()when testing the equality ofStringdata. (Solution: TriangleCalcStringTest.java) -
Review all vocabulary words from this section.