• 0

[Java] Method overloading while accepting input from a user


Question

I have got a problem.

I am trying to use method overloading to find the area of a rectangle. Only thing is the values have to be entered by the user. But if it has to accepted from the user, shouldn't we know the datatype of his input? And if we do, then the purpose of overloading becomes useless, because I already know the datatype.

Can you guys help me out?

You can add onto this code:

import java.io.*;
import java.lang.*;
import java.util.*;

class mtdovrld
{
void rect(int a,int b)
{
int result = a*b;
System.out.println(result);
}

void rect(double a,double b)
{
double result = a*b;
System.out.println(result);
}
}

class rectarea
{
public static void main(String[] args)throws IOException
{
mtdovrld zo = new mtdovrld();

Scanner input= new Scanner(System.in);

System.out.println("Pleaser values:");

// Here is the problem, how can I accept values from user where I do not have to specify datatype and will still be accepted by method?
double a = input.nextDouble();
double b = input.nextDouble();

zo.rect(a,b);

}
}

5 answers to this question

Recommended Posts

  • 0

The purpose of method overloading is not to duplicate code for each possible type; in fact, anytime your design implies duplicating code, it should make you raise an eyebrow. Here, both void rect(int, int) and void rect(double, double) use the exact same code. Also, since integers are implictly convertible to doubles, when you pass an integer to the method, the compiler could flag the call as ambiguous (but in Java I'm not sure).

Since integer and double multiplication are equivalent (well, for your purposes I guess), and that doubles include integers, you could just keep the double version and drop the integer version.

If you need a version of the method unique to different argument types but that does the same thing for each type, this calls for a generic method. Something like

void <T> rect(T a, T b) {
   // use T instead of int or double
}

  • 0

Also, I think the idea of accepting input from the user without knowing what is the type of input makes no sense, unless you want to go through the trouble of analysing the raw string to identify the type (if it's digits and there's a dot somewhere, it's a double, if it's alphanumerical characters, it's a string, etc.).

  • 0

I guess this is some kind of school project that you have been set? So debating how useful it is won't help?

Anyway, I think you are right, there's no way to input a number without committing to its type.

Is it worth showing us the original problem statement?

  • 0
  Dr_Asik said:
The purpose of method overloading is not to duplicate code for each possible type; in fact, anytime your design implies duplicating code, it should make you raise an eyebrow. Here, both void rect(int, int) and void rect(double, double) use the exact same code.

If you need a version of the method unique to different argument types but that does the same thing for each type, this calls for a generic method. Something like

void <T> rect(T a, T b) {
	// use T instead of int or double
 }

I was just trying to learn the basics of method overloading. So I just duplicated the code so that I can get a double result if the input is of the type double and int result if the input type is int.

I appreciate your help. But I didn't understand the code; we have to replace T with a data type right?

  JamesCherrill said:
I guess this is some kind of school project that you have been set? So debating how useful it is won't help?

Anyway, I think you are right, there's no way to input a number without committing to its type.

Is it worth showing us the original problem statement?

The question [came up with it myself] : Compile a program in the Java using method overloading to find the area of a rectangle based the data type of the input (int or double, by the user) and print the result with the same data type.

  • 0
  Unto Darkness said:
I appreciate your help. But I didn't understand the code; we have to replace T with a data type right?
No, you really write T. Or AnyType. Or any unused type identifier. At compile-time, T will be (in theory) replaced by the type of the arguments you provide. I say in theory because how Java does it is superficial and stupid, but you don't need to know about that right now. You can consider T as being a placeholder for the real type. The compiler will generate as many versions of your method as the number of types you call it with.

In other words, instead of duplicating the code yourself, like you did in your sample code, you let the compiler do it by replacing the type by a placeholder.

  Quote
I was just trying to learn the basics of method overloading. So I just duplicated the code so that I can get a double result if the input is of the type double and int result if the input type is int.
I understand, but that's not really the purpose of method overloading, hence you have trouble finding a test case that makes sense. If you need a method that does exactly the same thing ( = uses the exact same code) for different types, write a generic one as I proposed. Method overloading is mainly useful if you need to do something slightly different depending on the parameters provided. For instance, System.out.print() is overloaded for many different types because although the overall result is the same (the object gets displayed on the terminal), it's done somewhat differently for each type. When you do System.out.print(1.345), Java recognizes through string analysis, at compilation, that 1.345 is a float and by overloading, selects System.out.print(float f).
This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • I simply don't get why this "OS" exists. Who cares? Great, you can now run a Windows 95-era stupid game, super cool...
    • In the UK the standard edition has been priced at £69.99, the deluxe is £89.99, the super deluxe is .... £119.99 where the hell do they suggest these prices are coming from then! Sorry but at these prices I will not be buying when it comes out. It will be much, much later when the price has dropped considerably!
    • It'll just have $300 dlc instead, several season pass and at every moment you'll be left feeling you purchased the demo by buying the standard or deluxe editions, because the superdeluxe is how they meant to release the game in full.
    • Following higher pricing fears, Take-Two confirms Borderlands 4 won't be $80 by Pulasthi Ariyasinghe Video games going even higher in price has been a controversial subject as of late. Following the bump up to $70 in recent years, which has been vastly adopted by many publishers, now the price is slowly creeping up to be $80 for major releases. However, it seems Take-Two's latest game will not be following this new trend, despite what was being said in earlier reports. Take-Two and Gearbox today confirmed the launch of pre-orders for Borderlands 4, and front and center was the pricing information for the standard edition, which is set at $69.99. It seems the cooperative-focused looter shooter is not following in the footsteps of other high-profile $79.99 releases like Mario Kart World from Nintendo and the upcoming RPG The Outer Worlds from Microsoft. As for why many were expecting the Borderlands title to also be $80, Gearbox boss Randy Pitchford had alluded to the price hike recently. In a social media post in May, Pitchford answered a question from a fan regarding the game possibly being $80, to which he replied, saying that it was not his decision. "If you’re a real fan, you’ll find a way to make it happen," he went on to say, defending a possible $10 price hike. "My local game store had Starflight for Sega Genesis for $80 in 1991 when I was just out of high school working minimum wage at an ice cream parlor in Pismo Beach and I found a way to make it happen." In the end, Borderlands 4 is now confirmed to be releasing at $69.99 for the Standard Edition, with pre-orders available now. At the same time, a $99.99 Deluxe Edition and a $129.99 Super Deluxe Edition have also been confirmed, with each higher tier adding more cosmetic customizations as well as post-launch access to unannounced DLC content. Borderlands 4 launches September 12, 2025, across PC (Steam and Epic Games Store), Xbox Series X|S, and PlayStation 5. A Nintendo Switch 2 release is also planned to land later in 2025.
  • Recent Achievements

    • Explorer
      treker_ed went up a rank
      Explorer
    • Apprentice
      CHUNWEI went up a rank
      Apprentice
    • Veteran
      1337ish went up a rank
      Veteran
    • Rookie
      john.al went up a rank
      Rookie
    • Week One Done
      patrickft456 earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      641
    2. 2
      ATLien_0
      274
    3. 3
      +FloatingFatMan
      171
    4. 4
      Michael Scrip
      155
    5. 5
      Steven P.
      140
  • Tell a friend

    Love Neowin? Tell a friend!