![](/img/trans.png)
[英]splitting string by comma and space in order to store them into 2 different array
[英]Splitting an inputted string by comma and space
while(scan.hasNext()){
String line = scan.next();
String[] tempArray = line.split(",\\s*");
for (int i=0; i<3; i++){
System.out.println(tempArray[i]);
}
我的输入文件如下所示:
A, 0, 3
C, 2, 2
BB, 3, 3
DA, -3, 0
ED, 2, -2
它返回A,然后给我一个错误。 是什么赋予了?
我会用逗号分割,然后trim()
String
,
while(scan.hasNextLine()){ // <-- hasNextLine()
String line = scan.nextLine(); // <-- nextLine()
String[] tempArray = line.split(","); // <-- split on the comma.
for (int i=0; i<tempArray.length; i++){ // <-- use the array length
System.out.println(tempArray[i].trim()); // <-- trim() the String
}
}
String line = scan.next();
对于输入文件,您可以访问这个第一次, line
将等于"A,"
,这是不是你想要的。
这是因为Scanner#next()
仅读取直到空格字符为止,该空格字符出现在输入文件中A,
到0,
之间。 因此,为什么只返回A,
。
改为使用
String line = scan.nextLine();
它将读取直到换行。 因此,第一个循环会将line
设置为"A, 0, 3"
。
调试确实可以帮助提高编程能力。 打印出的回line
看到正在处理的内容可能与此有一定帮助。 然后能够弄清楚产生这些结果的原因要容易得多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.