2015-10-18 70 views
2

尝试final project for my friend's ICS class时,我遇到了这个奇怪的错误。为什么使用Scanner.next()会导致这种奇怪的System.out.println()行为?

其中一项任务是阅读this CSV file。这是我如何做它用扫描仪短SSCCE:

import java.io.File; 
import java.io.FileNotFoundException; 
import java.util.Scanner; 

public class Test { 

    public static void main(String[] args) { 

     Scanner fileScanner; 
     String inputFile = "input-project.csv"; 

     try { 
      fileScanner = new Scanner(new File(inputFile)); 
      fileScanner.useDelimiter("[,\n]"); 
      fileScanner.nextLine(); 

      while(fileScanner.hasNext()) { 
       String name = fileScanner.next(); 
       String number = fileScanner.next(); 
       System.out.println("Inserting " + name + " " + number + " (" + hash(name) + ")"); 
       //telephoneBook.insert(name, number); 
      } 

      fileScanner.close(); 
     } catch (FileNotFoundException e) { 
      System.out.println("ERROR: Input file " + inputFile + " was not found"); 
     } 
    } 

    public static Integer hash(String name) { 
     return name.hashCode() % 7; 
    } 
} 

它读取正常,但由于某些原因System.out.println("Inserting " + name + " " + number + " (" + hash(name) + ")")只打印" (" + hash(name) + ")"

看看这样的输出:

(5) 
(1) 
(4) 
(5) 
(3) 
(1) 
(4) 
(2) 
(2) 
(2) 

Process finished with exit code 0 

虽然与代码玩弄试图解决这个问题,我结束了不使用fileScanner.next()通过修复它。这是我目前的工作例如:

import java.io.File; 
import java.io.FileNotFoundException; 
import java.util.Scanner; 

public class Test { 

    public static void main(String[] args) { 

     Scanner fileScanner; 
     String inputFile = "input-project.csv"; 

     try { 
      fileScanner = new Scanner(new File(inputFile)); 
      //fileScanner.useDelimiter("[,\n]"); 
      fileScanner.nextLine(); // skip the first line 

      while(fileScanner.hasNext()) { 
       String[] line = fileScanner.nextLine().split(","); 
       String name = line[0]; 
       String number = line[1]; 
       //String name = fileScanner.next(); 
       //String number = fileScanner.next(); 
       System.out.println("Inserting " + name + " " + number + " (" + hash(name) + ")"); 
       //telephoneBook.insert(name, number); 
      } 

      fileScanner.close(); 
     } catch (FileNotFoundException e) { 
      System.out.println("ERROR: Input file " + inputFile + " was not found"); 
     } 
    } 

    public static Integer hash(String name) { 
     return name.hashCode() % 7; 
    } 
} 

这打印出预期:

Inserting HALL 123-4566 (5) 
Inserting BAKER 111-1111 (1) 
Inserting CARTER 222-2222 (4) 
Inserting KING 555-5555 (5) 
Inserting FOX 666-6666 (3) 
Inserting LEE 777-7777 (1) 
Inserting CASTRO 888-8888 (4) 
Inserting DAVIS 999-9999 (2) 
Inserting LONG 987-1234 (2) 
Inserting KAM 654-7890 (2) 

Process finished with exit code 0 

我现在的问题是:为什么这个解决这一问题?我错误地使用了.next()方法吗?

回答

2

您链接的CSV文件具有CRLF行结束符,但您的分隔符只能捕获\n。因此,\r会将其放入您的字符串中,并使输出格式看起来很奇怪。请改为使用不同的分隔符:

fileScanner.useDelimiter(",|\r?\n"); 
相关问题