-2

I have a method called "methodA". It have to called with two floats as inputs. I want to return a String. I need help showing how to call this method and assign the String it returns into the String variable str1. And we are assuming my method is in the same class that I call it from.

New to Java so a detailed beginner level explanation would be great! Thanks

public void methodA(f1,f2) {
    str1 = "" + f1 + f2;
    return str1;
}
seenukarthi
  • 8,241
  • 10
  • 47
  • 68
Tanner11
  • 11
  • 1
  • 6
  • A simple solution. `float f = 0.5f; String s = f +"";` – Uma Kanth Aug 21 '15 at 14:36
  • 1
    possible duplicate of [java : convert float to String and String to float](http://stackoverflow.com/questions/7552660/java-convert-float-to-string-and-string-to-float) – Swagin9 Aug 21 '15 at 14:40
  • A first problem is if you want to return the string you don't want the `return type` of the method to be `void` it should be `String`. – SwiftySwift Aug 21 '15 at 14:55

3 Answers3

2

As you are asking for a detailed explanation I will do my best. From what I can understand of your question you have a method methodA(float f1, float f2) (2 floats as input) and you want to return a String? (Correct me if this is not what you meant).

The "problem" here is that you are using floats (numbers) as input and you want to return text (simply explained, keep in mind that floats are not exact numbers). Java has a build-in method to do that, called toString.

Your code would look like this I guess:

public String methodA(float f1, float f2) {
    return Float.toString(f1) + "   " + Float.toString(f2);
}

To assign the result to the String variable, simply do

public String str;
str = methodA(float f1, float f2)

Now, in short what happened:

  1. your methodA receives two floats as input. It converts the two floats to Strings by the Float.toString(...) method and returns them. I added spaces between the two numbers for clarity (" ", you can delete this or add more)
  2. Create a String variable str and call the method on it. The variable now contains the two floats that are converted to a String.
  3. Now do with it what you want.

You said you were a beginner, so I gave a thorough explanation. Hope it helps.

0

Use return ""+(f1+f2); if you require the sum of numbers as a string.

Barett
  • 5,826
  • 6
  • 51
  • 55
-1

You can create a string like this:

Assuming your floats are f1 and f2,

str1 = "" + f1 + f2;

this is the short hand way to do it. But more official way is to

str1 = Float.toString(f1) + Float.toString(f2);

Refer This Question

EDIT:

as your edit show, you created a method. But if it has to return a string, you must set it's return type as String

edit it as

public String methodAB(Float f1, Float f2) {
  str1 = "" + f1 + f2;
  return str1;
}

OR Simply

return ("" + f1 + f2);
Community
  • 1
  • 1
ThisaruG
  • 3,222
  • 7
  • 38
  • 60