Java Reference
In-Depth Information
Now you've got a
DataAccess
class that will update and load from the database.
But there's no good way to connect it to the plugin yet, so we need to take a
look at that.
Convert
Location
to
String
and Back
Before we get much further, we may as well jump in and tackle the conversion
functions for a
Location
, as we'll need those before we start working on the
stack bits.
Converting a
Location
to a string is easy: just build a string from each of the
getX()
,
getY()
, and
getZ()
results using a non-numeric character to separate each
number. You could use spaces, or commas, but I prefer commas (“,”) as that
seems easier to read.
Write a function named
locationToString
that takes a
Location
and returns a
String
.
But now how to go the other way? Given a string that looks like
"110,75,220"
,
how can you split it up into three parts, one for each number?
Java to the rescue! In the Java doc under
String
, you'll find a function named
“
split
”, which takes a string and splits it up into an array. So if
str="110,75,220"
,
then
str.split(",");
would return an array of three strings, "110", "75", and "220".
Then it's just a matter of using
Double.parseDouble(string)
to convert each string
into a double. With the doubles, you can create a new
Location
.
Now you can write a function named
stringToLocation
that takes a
String
and
returns a
Location
.
When you're done, it might resemble this:
private String
locationToString(Location loc) {
return
loc.getX() +
","
+
loc.getY() +
","
+
loc.getZ();
}
private
Location stringToLocation(
String
str) {
String[]
arr = str.split(
","
);
double
x =
Double
.parseDouble(arr[0]);
double
y =
Double
.parseDouble(arr[1]);
double
z =
Double
.parseDouble(arr[2]);
return new
Location(x, y, z);
}
Make sure that much compiles, using
build.sh
as usual.