java中扫描仪关闭语句,在Java中使用扫描仪忽略字符

I want to take a multiple coordinate points, say (35,-21) (55,12)... from standard input and put them into respective arrays.

Let's call them x[] and y[].

x[] would contain {35, 55, ...} and y[] would contain {-21, 12, ...} and so forth.

However, I can't seem to find a way to get around the parenthesis and commas.

In c I was using the following:

for(i = 0; i < SIZE; i++) {

scanf("%*c%d%*c%d%*c%*c",&x[i],&y[i]);

}

However in Java I can not seem to find a way to get around the non-numeric characters.

I currently have the following in Java, as I am stuck.

double[] x = new double[SIZE];

double[] y = new double[SIZE];

Scanner sc = new Scanner(System.in);

for(int i=0; i < SIZE; i++) {

x[i] = sc.nextDouble();

}

So the question:

How would I ignore characters when reading in doubles from scanner?

A quick edit:

My goal is to keep the strict syntax (12,-55) on user input, and being able to enter multiple rows of coordinate points such as:

(1,1)

(2,2)

(3,3)

...

解决方案

I would do it in multiple steps for improved readability. First it's the System.in retrieving using a scanner and then you split in order to get each group of coordinates separately and then you can work on them later, for whatever purposes.

Something similar to this:

Scanner sc = new Scanner(System.in);

String myLine = sc.nextLine();

String[] coordinates = myLine.split(" ");

//This assumes you have a whitespace only in between coordinates

String[] coordArray = new String[2];

double x[] = new double[5];

double y[] = new double[5];

String coord;

for(int i = 0; i < coordinates.length; i++)

{

coord = coordinates[i];

// Replacing all non relevant characters

coord = coord.replaceAll(" ", "");

coord = coord.replaceAll("\\(", ""); // The \ are meant for escaping parenthesis

coord = coord.replaceAll("\\)", "");

// Resplitting to isolate each double (assuming your double is 25.12 and not 25,12 because otherwise it's splitting with the comma)

coordArray = coord.split(",");

// Storing into their respective arrays

x[i] = Double.parseDouble(coordArray[0]);

y[i] = Double.parseDouble(coordArray[1]);

}

Keep in mind that this is a basic solution assuming the format of the input string is strictly respected.

Note that I actually cannot fully test it but there should remain only some light workarounds.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值