(i) Identify and correct the errors in each of the following sets of code: [6 marks] i. while ( c <= 5 ) { product *= c; ++c; ii. if ( gender == 1 ) System.out.println( "Woman" ); else; System.out.println( "Man" ); iii. What is wrong with the following while statement? while ( z >= 0 ) sum += z;
(ii)Explain two (2) programming situations that will require the use of overloaded methods [5 marks]
public class Main
{
public static void main(String[] args) {
System.out.println("Hello World");
int product = 1;////initialization product variable
int c = 2;////initialization c variable
while (c <= 5) {
product *= c;
++c;
}
System.out.println(product);
int gender = 1;//initialization gender variable
if (gender == 1) {
System.out.println("Woman");
} else {
System.out.println("Man");
}
int z = 0;//initialization z variable
int sum = 2;//initialization sum variable
while (z <= 0) {
sum += z;
//Should be a break condition for stopping infinite while loop
break;
}
}
}
/*(ii)Suppose, you have to perform the addition of given numbers but there can be any number of arguments (let’s say either 2 or 3 arguments for simplicity).
In order to accomplish the task, you can create two methods sum2num(int, int) and sum3num(int, int, int) for two and three parameters respectively. However, other programmers, as well as you in the future may get confused as the behavior of both methods are the same but they differ by name.
The better way to accomplish this task is by overloading methods. And, depending upon the argument passed, one of the overloaded methods is called. This helps to increase the readability of the program.*/
Comments
Leave a comment