简体   繁体   中英

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

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?

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.
postalCodeIndex.findClosestBruteForce(latitude, longitude)

此方法本身会返回一个String,否则,您可能会喜欢

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

Based on the code you've given, the code inside the System.out.print() call will return a PostalCode object. So to get a string you could do something like:

String x = postalCodeIndex.findClosestBruteForce(latitude, longitude).toString();
//use x as String

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM