5/5 – (2 votes)
1) Write a static method called AreaOfRectangle that is passed two float-point values for the length and width of a rectangle. The method returns the product of the length and width as a double. Comment the method using javadoc conventions. Write a main method that creates the following variables to describe the sides of a rectangle:double length = 3.4;double width = 8.4;The main method should print the length, width, and area of the rectangle.
2) Why does the following code contain a compile-time error?public class Area{public static void main(String[] args){int x = 2;int y = 3;System.out.println(x: + x + y: + y + Sum: + sum(x,y));}/**Computes the sum of two arguments.@param a an int operand to be added@param b another int operand@return the sum of a and b*/public static int sum(int a, int b){return a + b;System.out.println(Finished adding);}}3) Run the following code. The sum method in this program violates a design principle of the book (that methods should not try to modify an argument) when it assigns 5 to a, and 6 to b. Certainly these values are changed; this can be seen by examining the value the sum method returns. But what about arguments x and y? Are their values changed, too? In other words: Do the assignments made in the method body have side effects in the main program?public class Area{public static void main(String[] args){int x = 2;int y = 3;System.out.println(x: + x + y: + y + Sum: + sum(x, y));}/**Computes the sum of two arguments.@param a an int operand to be added@param b another int operand@return the sum of a and b*/public static int sum(int a, int b){a = 5;b = 6;return a + b;}}4.1) Write a method called makeRow that is passed two arguments: an int n and a String s, and which returns a String containing n copies of s, concatenated in a row. For instance, if we call the method with makeRow(5, *), the method returns *****. Write a main method that uses the method to print the string *****=====*****.
4.2) Reuse makeRow to write a method called printUpTriangle that is passed two arguments, an int n and a String s. It should print a right triangle in which the base of the triangle is made of n copies of s, and the vertex of the triangle has a single copy of s on the right. For example, calling printUpTriangle(13, *); prints the following lines:*******************************************************************************************Write a main method that calls printUpTriangle(13, *).
4.3) Reuse makeRow by writing a method called printDownTriangle that is passed an int n and a String s, and that prints a right triangle in which the base (at the top) of the triangle is made of n copies of s, and the vertex of the triangle has a single copy of s on the right. For example, calling printDownTriangle(13, *); prints the following lines:*******************************************************************************************Write a main method that calls printDownTriangle(13, *).
Reviews
There are no reviews yet.