Computer Applications
Define a class to overload the method display as follows:
void display(): To print the following format using nested loop
5 5 5 5 5
4 5 5 5 5
3 4 5 5 5
2 3 4 5 5
1 2 3 4 5
void display(int n): To check and display if the given number is a Perfect number or not. A number is said to be perfect, if sum of the factors of the number excluding itself is equal to the original number.
E.g.
6 = 1 + 2 + 3, where 1, 2 and 3 are factors of 6 excluding itself.
Answer
import java.util.Scanner;
public class KboatMethodOverload
{
public void display()
{
for (int i = 0; i < 5; i++) {
for (int j = 5 - i; j <= 5; j++) {
System.out.print(j + " ");
}
for (int k = 4 - i; k > 0; k--) {
System.out.print("5 ");
}
System.out.println();
}
}
public void display(int n) {
int sum = 0;
for (int i = 1; i <= n / 2; i++) {
if (n % i == 0) {
sum += i;
}
}
if (n == sum)
System.out.println(n + " is a perfect number");
else
System.out.println(n + " is not a perfect number");
}
public static void main(String args[]) {
KboatMethodOverload obj = new KboatMethodOverload();
Scanner in = new Scanner(System.in);
System.out.println("Pattern: ");
obj.display();
System.out.println();
System.out.print("Enter a number: ");
int num = in.nextInt();
obj.display(num);
}
}Output
Related Questions
Define a class Student described as below
Data members/instance variables
name, age, m1, m2, m3 (marks in 3 subjects), maximum, averageMember methods
(i) Student (…) : A parameterised constructor to initialise the data members.(ii) compute() : To compute the average and the maximum out of three marks.
(iii) display() : To display the name, age, marks in three subjects, maximum and average.
Write a main method to create an object of a class and call the above member methods.
Define a class to input 15 integer elements in an array and sort them in ascending order using the bubble sort technique.
Define a class to enter a sentence from the keyboard and count the number of times a particular word occurs in it. Display the frequency of the search word.
E.g.
Input : Enter the sentence:
Hello, this is wow world
Enter the word:
wowOutput:
Searched word occurs 1 times.Define a class to accept 5 names in one array and their respective telephone numbers into a second array. Search for a name input by the user in the list. If found, display "search successful" and print the name along with the telephone number, otherwise display "Search unsuccessful: Name not enlisted".