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.