• 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

    • Forza Motorsport gets IndyCar, Career mode improvements, and more by Taras Buria Turn 10 Studios announced the next Forza Motorsport update, which includes new content and various game improvements. Update 21 follows the previous Anniversary Update and adds IndyCar, a free expansion for Career mode, Featured Tours, new reward cars, and more. IndyCar is back in the game, allowing you to get behind the wheel of the latest-generation open-wheel racing cars. New vehicles include the 2025 Chevrolet IndyCar and the 2025 Honda IndyCar. There is also the all-new IndyCar Series in Featured Multiplayer. Career mode now has the Champions Cup, a new home for racecar-focused tours in single-player racing. There, you can drive a variety of modern and classic racecars from one-make series to endurance legends. Completing the Champions Cup will give you various high-reward cars like the 1979 BMW #6 BMW Motorsport M1 Procar, the 1998 Nissan #23 Pennzoil NISMO Skyline GT-R, the 2014 Dodge #93 SRT Motorsports Viper GTS-R, and more. Developers also adjusted the in-game pricing for most racecars to make the Champions Cup more accessible. Another change in Update 21 is the return of previous Featured Tours. The game will feature an additional Tour every month, allowing you to earn some of the previous reward cars and participate in the now-ended events. Here is a brief overview of other changes and improvements: Featured Multiplayer has been reorganized, incorporating player feedback, with the goal of providing players with even more event variety. Click here for a rundown of these changes. We’ve implemented BoP Spec changes to the Forza GT2, Forza GT3, Forza Touring Car, and Forza Proto-H divisions with help from participants in the Forza Insiders Program. See the release notes for an overview of the adjustments that have been made. The Challenge Hub menu has been reorganized to more effectively communicate where rewards can be earned as well as the type of rewards available to unlock. We’ve fixed an issue for players using the Fanatec DD2 racing wheel that would assign the peripheral an incorrect mapping profile. All Builders Cup Tours are now immediately unlocked, which means you no longer need to complete the Modern Tour to access the 3 other Builders Cup Tours. In addition, select Builders Cup Series have been updated to feature additional eligible cars and post-launch tracks. A detailed overview of these changes has been included in the release notes. There are also numerous fixes to AI behavior and competitiveness in single-player racing. You can read more about Forza Motorsport Update 21 in a post on the official Forza website.
    • If it ever gets to a reasonable level of parity, I think more real competition in the Windows space would be a good thing. What I like about this is that it's not just another reskinned Linux distro (with all of those inherent problems). It's meant to literally boot and work like Windows NT+. That could be an interesting development one day -- note that this has been in development since 1996, btw.
    • 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.
  • 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
      639
    2. 2
      ATLien_0
      273
    3. 3
      +FloatingFatMan
      172
    4. 4
      Michael Scrip
      155
    5. 5
      Steven P.
      140
  • Tell a friend

    Love Neowin? Tell a friend!