In: Computer Science
java
In one program, write 3 separate functions, and use them.
1) Write the function body for each:
int squareInteger s( int x)
double squareDouble( double d)
float squareFloat ( float f)
They basically do the same thing, square a number, but use
different argument datatypes.
2) Test Each function with: Using int 4, double 4.9, float
9.4
What happened when you use the correct numerical data type as input
?
What happened when you use the incorrect numerical data types as
inputs ?
What is the lesson this teaches you about functions/methods ?
import java.util.*;
class DataTasks
{
int squareInteger(int x)
{
return(x*x);
}
double squareDouble(double d)
{
return(d*d);
}
float squareFloat(float f)
{
return(f*f);
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
DataTasks dt=new DataTasks();
System.out.print("Enter an integer : ");
int numInt=sc.nextInt();
System.out.println("Square Integer :
"+dt.squareInteger(numInt));
System.out.print("Enter a double : ");
double numDouble=sc.nextDouble();
System.out.println("Square Double:
"+dt.squareDouble(numDouble));
System.out.print("Enter a float : ");
double numFloat=sc.nextFloat();
System.out.println("Square Float :
"+dt.squareFloat(numFloat));
}
}
/*
Output :
Using int 4, double 4.9, float 9.4
Square Integer: 16
Square Double: 24.010000000000005
Square Float : error: incompatible types: possible lossy conversion
from double to float (Oracle JDK 1.8 or above)
What happened when you use the correct numerical data type as
input?
Then the answer will be the same as mentioned above.
What happened when you use the incorrect numerical data types as
inputs?
Then it will raise an exception for integer , suppose you entered
incorrect inputs like 4.5 for integer then it will raise an
exception
"Exception in thread "main" java.util.InputMismatchException"
For double it will execute properly if your enter integer then also
it will work properly even for float.
What is the lesson this teaches you about functions/methods?
Functions do return value while methods do not return any
value.
functions or methods values should be correct means actual and
formal variables should have the same data type, for integer, it
has to be same but for double it does not affect that much
*/