簡體   English   中英

讀取制表符分隔文件並忽略空格

[英]Read tab delimited file and ignore empty space

我正在開發一個簡單的項目,其中以制表符分隔的文本文件被讀入程序。

我的問題:在閱讀文本文件時,通常會有空數據空間。 缺乏數據導致意外輸出。 對於令牌[4]位置中沒有數據的行,忽略所有讀取的數據,並在運行System.out.println時顯示“4”(只是測試正確讀取數據)。 當我在令牌[4]位置中包含一個值時,數據讀取正常。 我在令牌[4]位置輸入一個值是不可接受的。 請參閱下面的文件和代碼。

2014    Employee    Edward Rodrigo  6500
2014    Salesman    Patricia Capola 5600    5000000
2014    Executive   Suzy Allen  10000   55
2015    Executive   James McHale    12500   49
2015    Employee    Bernie Johnson  5500    
2014    Salesman    David Branch    6700    2000000
2015    Salesman    Jonathan Stein  4600    300000
2014    Executive   Michael Largo   17000   50
2015    Employee    Kevin Bolden    9200    
2015    Employee    Thomas Sullivan 6250    

我的代碼是:

// Imports are here
import java.io.*;
import java.util.*;

public class EmployeeData {

public static void main(String[] args) throws IOException {
    // Initialize variables
    String FILE = "employees.txt";  // Constant for file name to be read
    ArrayList<Employee> emp2014;    // Array list for 2014 employees
    ArrayList<Employee> emp2015;    // Array list for 2015 employees
    Scanner scan;

    // Try statement for error handling
    try {
        scan = new Scanner(new BufferedReader(new FileReader(FILE)));
        emp2014 = new ArrayList();
        emp2015 = new ArrayList();

        // While loop to read FILE
        while (scan.hasNextLine()) {
            String l = scan.nextLine();
            String[] token = l.split("\t");
            try {
                String year = token[0];
                String type = token[1];
                String name = token[2];
                String monthly = token[3];
                String bonus = token[4];
                System.out.println(year + " " + type + " " + name + " " + monthly + " " + bonus);
            } catch (Exception a) {
                System.out.println(a.getMessage());
            }
        }
    } catch(Exception b) {
        System.out.println(b.getMessage());
    }
}

}

我收到的帶有“Employee”的行的輸出以意想不到的方式返回。

輸出:

run:
4
2014 Salesman Patricia Capola 5600 5000000
2014 Executive Suzy Allen 10000 55
2015 Executive James McHale 12500 49
4
2014 Salesman David Branch 6700 2000000
2015 Salesman Jonathan Stein 4600 300000
2014 Executive Michael Largo 17000 50
4
4
BUILD SUCCESSFUL (total time: 0 seconds)

我嘗試使用if-then來測試令牌[4]位置的空值,但這對我沒有幫助。 我做了很多搜索但沒有成功。

我對編程世界還很陌生,所以請原諒我的編碼效率低下。 非常感謝任何支持和一般反饋,以提高我的技能!

謝謝你,布萊恩

發生這種情況是因為您實際上正在獲取ArrayOutOfBoundsException ,並且消息為'4'。 因為索引4大於數組的長度。 你應該在你的catch語句中添加b.printStackTrace()因為這會在發生捕獲的異常時為你提供更多的詳細信息。

你可以通過添加以下內容來解決這個問題:

String bonus = "";
if(token.length > 4)
    bonus = token[4];

由於ArrayOutOfBoundsException ,Java Devil是正確的底層問題。 但它也值得探索為什么你沒有看到這一點。 正如我們在評論中所討論的那樣,你的“錯誤處理的嘗試聲明”實際上根本不是處理你的錯誤,而是壓制它們 ,這通常是一個糟糕的計划,因為它允許你的程序在你的假設之后繼續運行(那個它正常工作)已被違反。

這是一個稍微清理過的代碼版本。 導致ArrayOutOfBoundsException的潛在問題仍然存在,但如果您以這種方式構建代碼,問題就會立即顯現出來。 有一些評論稱內聯問題。

public class EmployeeData {
  // constants should be declared static and final, and not inside main
  private static final String FILE = "employees.txt";

  // If you have an exception and you don't know how to handle it the best thing
  // to do is throw it higher and let the caller of your method decide what to do.
  // If there's *nothing* you want to do with an exception allow main() to throw
  // it as you do here; your program will crash, but that's a good thing!
  public static void main(String[] args) throws IOException {
    // Notice the <> after ArrayList - without it you're defining a "raw type"
    // which is bad - https://stackoverflow.com/q/2770321/113632
    ArrayList<Employee> emp2014 = new ArrayList<>();
    ArrayList<Employee> emp2015 = new ArrayList<>();

    // A try-with-resources block automatically closes the file once you exit the block
    // https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
    try (Scanner scan = new Scanner(new BufferedReader(new FileReader(FILE)))) {
      while (scan.hasNextLine()) {
        String l = scan.nextLine();
        String[] token = l.split("\t");
        // The code below this line assumes that token has at least five indicies;
        // since that isn't always true you need to handle that edge case before
        // accessing the array indicies directly.
        String year = token[0];
        String type = token[1];
        String name = token[2];
        String monthly = token[3];
        String bonus = token[4];
        System.out.println(year + " " + type + " " + name + " " + monthly + " " + bonus);
      }
    }
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM