1

I need to write a program which uses multiple methods called average which return the average of those values, if both are ints the value returned should be an int, and if one or more is a floating point number, the value should be returned as a double. I keep running into errors with the following code:

class Main
{
  class Unbruh{
  static int average(int x, int y)
  {
    return ((x + y) / 2);
  }
  static double average(double x, double y)
  {
    return ((x + y) / 2);
  }
}
  class Bruh
  {
  public static void main (String[] args)
  {

    System.out.println ("Enter number");
    Scanner input = new Scanner (System.in);
    float x = input.nextFloat ();
    float y = input.nextFloat ();
    System.out.println(Unbruh.average(x,y));
System.out.println(Unbruh.average(x,y));

    Unbruh a = new Unbruh ();
    a.average (x, y);
 // System.out.println (average (x, y));
 
  }

}
}

Is something wrong with the logic here, or is there just formatting errors?

Katzerax
  • 21
  • 4
  • It's just formatting. Move the `Unbruh` class outside of the one that contains main. See my example. `Bruh` should be declared public. – WJS Feb 11 '21 at 03:32
  • "I keep running into errors with the following code" What errors ? Compile time ? Run time ? – John3136 Feb 11 '21 at 04:18
  • 1
    Katzerax, if any of these answers have been helpful, please consider upvoting them. Also if one of these stands out to you and solves your problem, mark it as the correct answer. You might not have enough reputation to upvote. If that's the case, it's fine. – hfontanez Feb 11 '21 at 15:58

3 Answers3

0

The method main cannot be declared static; static methods can only be declared in a static or top level type.

That comes from declaring a static method inside a class that is inside another class. That other class is not considered a top level class.

I modified the code to demonstrate that overloading will select the proper method based on the argument types. That means calling the methods with either ints or floats. Using a single float and the float method will be called. Using two ints and the int method will be called.

Note: (And this is important). If you prompt for ints or type in ints and assign to a float, then the float method will be called. Even if you prompt for floats and type in 10 and 20 the float method will be called. This is not about what you typed in but the types to which the values were assigned.

Checking for the presence of a decimal to determine if the user wanted to use a float won't work since both Scanner.nextFloat() will accept a value sans decimal point as will Float.parseFloat(). Neither will throw an exception. Thus it is not possible to determine the actual intent of the user. And imo, forcing a user to supply a decimal point is unreasonable.

My suggestion is that you drop the following code as is directly into a file called Bruh.java. There is no reason that I can think of that should prevent this from working as I just did it myself. Sorry you have been struggling with this issue.

import java.util.Scanner;

class Unbruh {
    static int average(int x, int y) {
        System.out.println("Calling int version");
        return ((x + y) / 2);
    }
    
    static float average(float x, float y) {
        System.out.println("Calling float version");
        return ((x + y) / 2);
    }
}

public class Bruh {
    public static void main(String[] args) {
        
        System.out.println("Enter two float numbers.");
        Scanner input = new Scanner(System.in);
        float x = input.nextFloat();
        float y = input.nextInt(); // converted to a float
        float floatResult = Unbruh.average(x, y);
        System.out.println(floatResult);

        System.out.println("Enter two int numbers.");
        int xx = input.nextInt();
        int  yy = input.nextInt();
        int intResult = Unbruh.average(xx, yy);
        System.out.println(intResult);
        
        x = xx; // converting int to float
        y = yy; // converting int to float
        // float method will be called.
        
        floatResult = Unbruh.average(x,y);
        System.out.println(floatResult);
    }
}

Here is what a session might look like

Enter two float numbers.
10 20                         <-- user input
Calling float version
15.0
Enter two int numbers.
10 40                         <-- user input
Calling int version
25
Calling float version
25.0
WJS
  • 36,363
  • 4
  • 24
  • 39
  • Getting error `The public type Bruh must be defined in its own file`. Is this likely a limitation with drjava? – Katzerax Feb 11 '21 at 03:45
  • Nope. That is a Java requirement. So just rename the file to `Bruh.java` and it should work. The other class, not being public may still be in the same file. Only one public outer class per file is permitted. And if there is a static main entry point, that is the one that must contain it. – WJS Feb 11 '21 at 03:47
  • Alright, renamed the file, running this causes a few of the same error: `The method main cannot be declared static; static methods can only be declared in a static or top level type`. This occurs for all instances of static in the program – Katzerax Feb 11 '21 at 03:53
  • I modified my statement since it was not interpreted as I meant it. – WJS Feb 11 '21 at 17:26
0

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

Edgar Magallon
  • 556
  • 2
  • 7
  • 15
  • Only use this code, and name your file like **Bruh.java** to can work. – Edgar Magallon Feb 11 '21 at 04:18
  • @Katzerax I didn't get any error. Maybe it's for the java version I have. I've compiled in java 11 and it works, but, I guess this can work for java 8 too. Check please if you java version is java 8 or major. See this [question](https://stackoverflow.com/questions/24301986/the-type-java-lang-charsequence-cannot-be-resolved-in-package-declaration) may help you. – Edgar Magallon Feb 11 '21 at 04:40
0

Your problem is that, no matter what you enter from the console (i.e. 4 2 or 4.0 2.0), the fact is that you are capturing these as floats and the same method will be called (the one that returns a float).

The way I would do this is to keep the digits as Strings and create a single method that evaluates the input strings and evaluates them based on the string pattern. If the string contains a period, assume it is a floating point number. If it doesn't, assume it is an integer. If you try to convert the string into a number AND it is not a number, the method will throw a NumberFormatException.

Once you have the strings converted to numbers, if BOTH numbers are integers, return an integer. Else, return a double. You can track this by simply using a isFloat flag to remember that at least one of the inputs were a floating point number. The solution is included below and it is not that complicated.

public Number average(String x, String y) throws NumberFormatException {
    
    Number d1;
    Number d2;
    boolean isFloat = false;
    
    if (x.contains(".")) {
        d1 = Double.parseDouble(x);
        isFloat = true;
    } else {
        d1 = Integer.parseInt(x);
    }
    
    if (y.contains(".")) {
        d2 = Double.parseDouble(y);
        isFloat = true;
    } else {
        d2 = Integer.parseInt(y);
    }
    
    if (isFloat) {
        return (d1.doubleValue() + d2.doubleValue()) / 2.0;
    }
    
    return (d1.intValue() + d2.intValue()) / 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();
    input.close();
    Unbruh a = new Unbruh();
    System.out.println(a.average(x, y));
  }
}

The outputs using the modified Bruh class:

4
2
3

4.0
2.0
3.0

4.0
2
3.0

4
2.0
3.0
hfontanez
  • 5,774
  • 2
  • 25
  • 37
  • @Katzerax I didn't get any errors. Try my modified `Bruh` class – hfontanez Feb 11 '21 at 04:33
  • I'm getting "The method contains(java.lang.CharSequence) from the type java.lang.String refers to the missing type java.lang.CharSequence" as an error on each if statement, is there a fix for this? – Katzerax Feb 11 '21 at 04:37
  • @Katzerax, Your `Bruh` class should be replaced with mine, and the `Unbruh` class should contain a single `average` method, which is the one I showed on this post. – hfontanez Feb 11 '21 at 04:42