在Java中使用扫描仪忽略字符 [英] Ignoring characters using Scanner in Java
问题描述
我想从标准输入中获取多个坐标点,例如(35,-21)(55,12)...,并将它们放入各自的数组中.
I want to take a multiple coordinate points, say (35,-21) (55,12)... from standard input and put them into respective arrays.
我们称它们为x []和y [].
Let's call them x[] and y[].
x []将包含{35,55,...},而y []将包含{-21,12,...},依此类推.
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.
在c中,我使用了以下内容:
In c I was using the following:
for(i = 0; i < SIZE; i++) {
scanf("%*c%d%*c%d%*c%*c",&x[i],&y[i]);
}
但是,在Java中,我似乎找不到解决非数字字符的方法.
However in Java I can not seem to find a way to get around the non-numeric characters.
由于受困,我目前在Java中拥有以下内容.
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:
我的目标是在用户输入上保留严格的语法(12,-55),并能够输入多行坐标点,例如:
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) ...
(1,1) (2,2) (3,3) ...
推荐答案
我将分多个步骤进行操作,以提高可读性.首先是System.in,它使用扫描仪进行检索,然后进行拆分以分别获取每组坐标,然后可以出于任何目的稍后对其进行处理.
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.
类似的东西:
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.
这篇关于在Java中使用扫描仪忽略字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!