0

I have been working on a project for school. Basically you have to make a script with a couple of scanners. So for instance:

  • Return the corresponding ASCII code from a integer, so from a scanner
  • Return the surface of a sphere by giving a double.

I now want to make a Scanner class for both functions. But 1 has to be an integer and the second has to be a double. How do I make sure wether the function returns a double or an integer.

I am using the follow code:

public static [Heres what goes wrong] vrager (String type, String tekst) {

Scanner vraag = new Scanner(System.in);

System.out.println(tekst);

type variable = vraag.next();

return variable;

So by calling the function would be like: seconden = (vrager("int", "How many seconds?:));

But if I would like to let the function work for also doubles it goes wrong cause the function is not expecting to return doubles.

How can I solve this issue?

Sgoettschkes
  • 13,141
  • 5
  • 60
  • 78
Kipt Scriddy
  • 743
  • 2
  • 14
  • 22

2 Answers2

11

A double can represent every possible int value so return a double.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
3

You cannot have two functions with the same name, same parameters but different types. There are at least a couple of way to implement it, you can do it as:

public static Number vrager (String type, String tekst) {
    ...
    Double ret=....
    --- or ---
    Integer ret....
    return ret;
}

Look at the documentation for the class Number

Another way is to use generics: How do I make the method return type generic?

Community
  • 1
  • 1
thedayofcondor
  • 3,860
  • 1
  • 19
  • 28