To determine if a number is integer or float, you should read the number as a String. In this case you are reading the numbers as floats and that may not work to determine what you want (or maybe there is a way to do that how you have your code, I don't know).
So, if you read the line as a String and check if this contains a .
, if does, then, that's a float number, but here, you must be careful, because if you input any string, that will cause a NumberFormatException when the String it's converted to Float or Integer.
You can try something like this in your code:
import java.util.Scanner;
class Unbruh {
static int average(int x, int y) {
System.out.println("Integer numbers");
return ((x + y) / 2);
}
static float average(float x, float y) {
System.out.println("Float numbers");
return ((x + y) / 2);
}
}
public class Bruh {
public static void main(String[] args) {
System.out.println("Enter number");
Scanner input = new Scanner(System.in);
String x = input.next();
String y = input.next();
if(x.contains(".") || y.contains("."))
{
System.out.println(Unbruh.average(Float.parseFloat(x), Float.parseFloat(y)));
}
else{
System.out.println(Unbruh.average(Integer.parseInt(x), Integer.parseInt(y)));
}
Unbruh a = new Unbruh();
if(x.contains(".") || y.contains("."))
{
System.out.println(a.average(Float.parseFloat(x), Float.parseFloat(y)));
}
else{
System.out.println(a.average(Integer.parseInt(x), Integer.parseInt(y)));
}
// System.out.println (average (x, y));
}
}
And about your code, you have a little warning, because you have a.average(...)
where a
is an instance from Unbruh class. But, the methods inside that class are static, thus, it's not necessary to use a.average(...)
that's not recommended.
For static methods, identifiers you have to use the follow syntax:
className.static_method(...)
In this case, in your code you have that syntax, in the lines:
Unbruh.average(...)
If you see, you are using the name class Unbruh and then, the static method
PD: When I say that you input any string can cause a NumberFormatException I mean that, if you input a string like "fuzz", that will cause the error, but If you input "10" or "20.5" that is correct, so when you use the parse method, it will not throw a NumberFormatException