问题
How can I scan coordinates with (x, y)
format?
For example:
(1, 3)
(2, 4)
(4, 1)
(3, 2)
What I've tried is this:
String m = input.next();
String parts[] = m.split(",");
String part1 = parts[0];
String part2 = parts[1];
part1 = part1.substring(1, part1.length());
part2 = part2.substring(0, part2.length()-1);
That code works for a coordinate with (x,y)
format but doesn't work for (x, y)
回答1:
You mentioned you could get it working with format (x,y)
but not (x, y)
with the space in between. I would suggest using .trim()
to get rid of the spaces:
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.println("Enter a coordinate: ");
String coordinate = input.nextLine();
String[] parts = coordinate.split(",");
// if input is (x, y)
// then parts[0] is "(x"
// and parts[1] is " y)"
String x = parts[0].trim().substring(1).trim();
String y = parts[1].trim().substring(0, parts[1].trim().length() - 1).trim();
System.out.println("x: " + x + "\ny: " + y);
}
I trimmed the part before getting the substring, and then trimmed the part after getting the substring as well, so that when the brackets are ignored in the substrings, the spaces will also be removed. It seems to work for all cases no matter how much whitespace there is.
Samples:
Without a space
Enter a coordinate: (155,54) x: 155 y: 54
With a space
Enter a coordinate: (118, 43) x: 118 y: 43
With a lot of spaces
Enter a coordinate: ( 155 , 4 ) x: 155 y: 4
回答2:
Here's an outline for one way to go about doing this:
- Instantiate a
Scanner
object. - Read the next token (the next line) from it with the
next()
method. - Split the read in
String
on the comma and save the resulting array into aString[]
- e.g.nums[]
. - For the first number, parse the first string in the
String[]
from the 2nd character (at index 1, not 2) onwards into anint
. You can useInteger.valueOf()
andsubstring(1)
to do this. - For the second number, substring from the 1st character of the second string in the
nums[]
array (index 0) until the character before the last character. Sosubstring(0, nums[1].length()-1)
. Again, useInteger.valueOf()
.
Hopefully that helps and doesn't completely give away the solution without some more effort on your part. Also, note that you should handle exceptions that might pop up.
来源:https://stackoverflow.com/questions/21665910/java-scan-coordinates-as-x-y-format