简体   繁体   English

用逗号和空格分隔输入的字符串

[英]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]);
        }

My input file looks like: 我的输入文件如下所示:

A, 0, 3 
C, 2, 2 
BB, 3, 3 
DA, -3, 0 
ED, 2, -2

It returns A, then gives me an error. 它返回A,然后给我一个错误。 What gives? 是什么赋予了?

I would split on comma and then trim() the String , 我会用逗号分割,然后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();

For your input file, the first time you access this, line will be equal to "A," , which is not what you wanted. 对于输入文件,您可以访问这个第一次, line将等于"A," ,这是不是你想要的。

This is because Scanner#next() only reads up until a whitespace character, which is present in the input file between A, and 0, . 这是因为Scanner#next()仅读取直到空格字符为止,该空格字符出现在输入文件中A,0,之间。 Hence, why only A, is returned. 因此,为什么只返回A,

Instead use 改为使用

String line = scan.nextLine();

Which will read up until a line break. 它将读取直到换行。 So the first loop will set line to "A, 0, 3" . 因此,第一个循环会将line设置为"A, 0, 3"


Debugging can really help improve programming abilities. 调试确实可以帮助提高编程能力。 Printing out the return of line to see what is being processed could have definitely helped with this. 打印出的回line看到正在处理的内容可能与此有一定帮助。 Being able to then figure out what is happening to produce those results is a lot easier. 然后能够弄清楚产生这些结果的原因要容易得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM