7
Define a class to overload the method print() as follows:
void print() – To print the given format using nested loops.
Show SolutionHide Solution↓
@#@#@
@#@#@
@#@#@
@#@#@
double print(double a, double b) – To display the sum of numbers between a and b with difference of 0.5.
e.g. if a = 1.0, b = 4.0
Output is: 1.0 + 1.5 + 2.0 + 2.5 + … + 4.0
int print(char ch1, char ch2) – Compare the two characters and return the ASCII code of the largest character.
import java.util.Scanner;
class Overload {
public void print() {
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 5; j++) {
if (j % 2 == 0) {
System.out.print('@');
}
else {
System.out.print('#');
}
}
System.out.println();
}
}
public double print(double a, double b) {
double sum = 0.0;
for(double i = a; i <= b; i += 0.5)
sum += i;
System.out.println("Sum = " + sum);
return sum;
}
public int print(char ch1, char ch2) {
int maxAscii = (ch1 > ch2) ? (int)ch1 : (int)ch2;
System.out.println("Larger ASCII code = " + maxAscii);
return maxAscii;
}
public static void main(String[] args) {
Overload obj = new Overload();
Scanner sc = new Scanner(System.in);
System.out.println("Pattern:");
obj.print();
System.out.print("\nEnter two decimal values (a and b): ");
double a = sc.nextDouble();
double b = sc.nextDouble();
obj.print(a, b);
System.out.print("\nEnter two characters: ");
char ch1 = sc.next().charAt(0);
char ch2 = sc.next().charAt(0);
obj.print(ch1, ch2);
}
}
