Reputation: 83
I am new to java programming. I am having a problem on how to use the method for char
here. What do you return in the char
method to get the average of the ASCII values in the main body? Thanks!
public static int average(int i,int j)
{
return (i + j) / 2;
}
public static double average(double a,double b)
{
return (a + b) / 2;
}
public static char average(char first,char second)
{
return ?;
}
public static void main(String[] args)
{
char first = 'a', second = 'b';
int i = 5, j = 12;
double a = 5.5, b = 8.5;
System.out.println("Average of (x,y) is : " + average(first,second));
System.out.println("Average of (a,b) is : " + average(a,b));
System.out.println("Average of (i,j) is : " + average(i,j));
}
Upvotes: 1
Views: 110
Reputation: 48287
Chars are at the end ints, so the average char makes no much sense since the result will be char again, i.e consider this case: what is the average between 'a' and 'b'? a is represented with 97, b with 98, ave = 97.5 but there is no char value for 97.5, in fact, that will be rounded to int pointing to 97 again, so average for 'a' and 'b' is 'a', kind of weird isnt ?
Anyway you can do
public static char average(char first,char second)
{
return (char) ( (first + second) / 2);
}
note that since dividing by int literal 2 you will need to cast the result to char again..
Upvotes: 1
Reputation: 22442
In Java, char
values are automatically typecasted to int
type.
As you have already got average(int i,int j)
, you don't need to write any average(char first,char second)
.
So when you call average(first,second))
, then the method which take int
arguments i.e., average(int i,int j)
will be invoked.
Upvotes: 0