How do I convert the content of System.out.print to a String variable in java


Question

I have this line of code:

    System.out.print(postalCodeIndex.findClosestBruteForce(latitude, longitude));

It returns output from a text file that was ran through an algorithm. For example the output is can be : "A0E 2Z0 Monkstown Newfoundland NL D [47.150300:-55.299500]". I would like to convert that output to a string so I can use it in a javafx GUI text. Is that posible?

1
-1
4/17/2014 5:27:55 AM

Accepted Answer

System.out.print accepts a String as a parameter, in fact, anything that you send it will be converted to a String in order for it to be displayed.

Using the following code, you could then put the result of the postalCodeIndex method call into a variable called myString.

String myString = postalCodeIndex.findClosestBruteForce(latitude, longitude).toString();

It might be worth your while remembering that the process in the System.out.print() code sample works as follows:

  1. postalCodeIndex is called FIRST, creating a temporary String in-place because the .toString() method is called on your behalf.
  2. The System.out.print method is only called AFTER the postalCodeIndex method has returned, because System.out.print requires this returned String to enable it to print something to the console.
7
4/17/2014 5:33:20 AM

postalCodeIndex.findClosestBruteForce(latitude, longitude)

this method it self would returning a String or if not you can do like

String str = postalCodeIndex.findClosestBruteForce(latitude, longitude).toString();

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon