Program to overload a function display(…) and perform the given tasks:
- void display(int n) – To check whether the number is Perfect Square or not.
- void display(String str,char ch) – To search and print for a specific character in a word.
- void display(String str) – To search and print only the special characters in a string.
Take all required inputs from main functions and invoke the function using class object.
Java
import java.util.*;
public class DisplayOverload
{
public void display(int n)
{
double sqrt=Math.sqrt(n);
if(sqrt-Math.floor(sqrt)==0)
{
System.out.println(n+" is a perfect sqaure");
}
else
{
System.out.println(n+" is not a perfect sqaure");
}
}
public void display(String str,char ch)
{
str=str.trim();
int l=str.length(),flag=0;
for(int i=0;i<l;i++)
{
if(ch==str.charAt(i))
{
flag=1;
break;
}
}
if(flag==1)
{
System.out.println("'"+ch+"' is present in the word");
}
else
{
System.out.println("'"+ch+"' is not present in the word");
}
}
public void display(String str)
{
str=str.trim();
int l=str.length();
char ch=' ';
System.out.print("Special characters: ");
for(int i=0;i<l;i++)
{
ch=str.charAt(i);
if(!((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z')||(ch>='0'&&ch<='9')))
{
System.out.println(ch);
}
}
}
public static void main(String args[])
{
int n=0;
String str="";
char ch=' ';
Scanner sc=new Scanner(System.in);
DisplayOverload ob=new DisplayOverload();
System.out.print("Enter a number: ");
n=sc.nextInt();
ob.display(n);
System.out.print("Enter a word: ");
str=sc.next();
System.out.print("Enter a character to search: ");
ch=sc.next().charAt(0);
sc.nextLine();
ob.display(str,ch);
System.out.print("Enter a string: ");
str=sc.nextLine();
ob.display(str);
}
}Java