我想取多个坐标点,比如说(35,-21((55,12(...从标准输入并将它们放入各自的数组中。
我们称它们为 x[] 和 y[]。
x[] 将包含 {35, 55, ...},y[] 将包含 {-21, 12, ...} 等等。
但是,我似乎找不到绕过括号和逗号的方法。
在c中,我使用了以下内容:
for(i = 0; i < SIZE; i++) {
scanf("%*c%d%*c%d%*c%*c",&x[i],&y[i]);
}
但是在Java中,我似乎找不到绕过非数字字符的方法。
我目前在 Java 中有以下内容,因为我被卡住了。
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();
}
所以问题来了: 从扫描仪读取双精度时如何忽略字符?
快速编辑:
我的目标是在用户输入时保持严格的语法(12,-55(,并能够输入多行坐标点,例如:
(1,1( (2,2) (3,3) ...
nextDouble()
尝试从输入中获取双精度数。它根本不意味着解析输入流并自行计算如何解释该字符串以以某种方式提取数字。
从这个意义上说:仅靠扫描仪在这里根本不起作用。您可以考虑使用分词器 - 或者使用scanner.next()
返回完整的字符串;然后进行手动拆分/解析,或者转向正则表达式来执行此操作。
我会分多个步骤进行以提高可读性。首先是使用扫描仪检索 System.in,然后您拆分以分别获取每组坐标,然后您可以稍后出于任何目的处理它们。
类似于这样的东西:
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]);
}
请记住,这是一个基本解决方案,假设严格遵守输入字符串的格式。
请注意,我实际上无法完全测试它,但应该只保留一些简单的解决方法。
提到用户输入严格限制为 (12,-55( 或 (1,1( (2,2( (3,3( ...格式以下代码工作正常
Double[] x = new Double[5];
Double[] y = new Double[5];
System.out.println("Enter Input");
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
input = input.trim();
int index = 0;
while(input != null && input != "" && input.indexOf('(') != -1) {
input = input.trim();
int i = input.indexOf('(');
int j = input.indexOf(',');
int k = input.indexOf(')');
x[index] = Double.valueOf(input.substring(i+1, j));
y[index] = Double.valueOf(input.substring(j+1, k));
System.out.println(x[index] + " " + y[index]);
input = input.substring(k+1);
index++;
}
在这里,我以字符串格式获取了用户输入,然后对其调用 trim 方法以删除前导和尾部空格。
在 while 循环中,'(' 和 ',' 之间的子字符串被取到 x[] 中,',' 和 '('之间的子字符串被取到y[]中。
在循环中,索引递增,输入字符串在第一次出现'('之后修改为子字符串,直到字符串末尾。
重复循环,直到没有出现"(">或输入为空。