• 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

    • That is typically how his products go. They start off with a photoshopped image or slapped together pre-production sample. If they get enough orders, they make them, if they don't, they cancel and send refunds. Art of the deal, lol.
    • The idea of an adversary saying "oh darn it, the keys are on a TPM chip so we can't get them" is probably too good to be true.
    • PowerToys is getting a big Dashboard redesign by Taras Buria PowerToys currently has 28 utilities to enhance your user experience (the latest addition arrived in April). You can check out the list of all modules and quickly toggle them on or off on the dedicated Dashboard page that greets you each time you open PowerToys. However, with the increasing list of tools and their vast customizability, many may feel that the Dashboard is a bit undercooked and lacks more polish and useful features. If you think so, Microsoft has some good news for you. In a new PR on PowerToys' GitHub, Microsoft engineers agree that the Dashboard needs improvements, even though it worked fine in earlier days with fewer modules. The proposed solution for the overcrowded Dashboard is a redesigned variant, which looks more similar to the Windows 11 Settings app. With the suggested variant, you get much more from Dashboard: a quick link to the latest changelog, various warnings that need your attention (like conflicting shortcuts), an update button, Quick Launcher, shortcuts for your modules, and a list of available tools. A search box for modules and settings is also there to help you find stuff that you need. Here is how Niels Laute, a software engineer working on WinUI and PowerToys, describes the proposed redesign: Since PowerToys is an open-source project, other developers are welcome to contribute their ideas. One of those ideas is implementing SplitView so that you can open each module's settings without leaving the Dashboard page. Unfortunately, there is no information on when Microsoft will ship the redesigned Dashboard. While we wait for the June 2025 update, check out these three useful plugins for PowerToys Run. What other changes would you like Microsoft to add to PowerToys? Share your thoughts in the comments.
    • But AI is not turned off completely, you can hide stuff, but AI is still there, even on Windows 10 to a lesser extent. You use different MS apps on Windows 11 and again 10 to a lesser extent and AI is there, sure you don't have to use it, but why not just give an easy option to disable all AI? Even Google does that on Android. If you don't think that the MS account is not forced, then I do wonder what you think is forced. Sorry, but it is forced, try and install Windows 10 and 11 without an MS account? You will find that you can't officially, sure there are some ways to get around to and even those are getting more difficult to use as MS decides to stop people using them. My Mac on set up ask you if you have an Apple account, but it is so easy to say, nope, I have not got one. I don't understand why the pushing for an MS account, not all of us want to use the cloud for storage and for most people that is the only advantage of having an MS account, unless you play some games. I have heard that Windows 11 still pop up about using Edge when people don't certainly on updates. I get a pop-up on my Windows 10 machine now and again saying let's finish setting up. It is set up, what they want me to do is to say what I am using the computer for. Nothing to do with them, no idea what they do if I go ahead with what ever they want me to do as I skip, but there should be a no, thanks. I don't use the search in Windows, never have, unless I am looking for files, I use Duck Duck go in my default browser, but some people do, and they should not be forced to use Bing, which in the UK is a load of poop and then if they do click on an in it should open in the default browser.. This is the sort of thing I expected from Apple, Microsoft is far worse than Apple. Context menus again, people should not have to do tweaks, it should be a simple setting.
  • Recent Achievements

    • Week One Done
      patrickft456 earned a badge
      Week One Done
    • One Month Later
      patrickft456 earned a badge
      One Month Later
    • One Month Later
      Jdoe25 earned a badge
      One Month Later
    • Explorer
      Legend20 went up a rank
      Explorer
    • One Month Later
      jezzzy earned a badge
      One Month Later
  • Popular Contributors

    1. 1
      +primortal
      636
    2. 2
      ATLien_0
      275
    3. 3
      +FloatingFatMan
      171
    4. 4
      Michael Scrip
      155
    5. 5
      Steven P.
      132
  • Tell a friend

    Love Neowin? Tell a friend!