java scan coordinates as (X, Y) format

白昼怎懂夜的黑 提交于 2019-12-13 06:29:02

问题


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:

  1. Without a space

    Enter a coordinate: 
    (155,54)
    x: 155
    y: 54
    
  2. With a space

    Enter a coordinate: 
    (118, 43)
    x: 118
    y: 43
    
  3. 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:

  1. Instantiate a Scanner object.
  2. Read the next token (the next line) from it with the next() method.
  3. Split the read in String on the comma and save the resulting array into a String[] - e.g. nums[].
  4. For the first number, parse the first string in the String[] from the 2nd character (at index 1, not 2) onwards into an int. You can use Integer.valueOf() and substring(1) to do this.
  5. 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. So substring(0, nums[1].length()-1). Again, use Integer.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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!