Java扫描坐标为(X,Y)格式 [英] java scan coordinates as (X, Y) format

查看:67
本文介绍了Java扫描坐标为(X,Y)格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何扫描(x, y)格式的坐标?
例如:

How can I scan coordinates with (x, y) format?
For example:

(1, 3) 
(2, 4)
(4, 1)
(3, 2)

我尝试过的是这个

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);

该代码适用于(x,y)格式的坐标,但不适用于(x, y)

That code works for a coordinate with (x,y) format but doesn't work for (x, y)

推荐答案

您提到可以使用(x,y)格式,但不能使用(x, y)格式,并且中间必须留有空格.我建议使用.trim()摆脱空格:

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.

样品:

  1. 没有空格

  1. 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  
    

  • 这篇关于Java扫描坐标为(X,Y)格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆