2015-11-07 27 views
0

我對Java非常陌生,正如您可以從我的代碼中看到的那樣。歡迎任何幫助:)java使用append從文件的一行中提取數據

我有一個文件包含線,如:在文件

列:7

確切的文件數量(行):118

確切的文件記錄長度(字節數變量塊):52

我想用append來提取標籤後面的數字,但它返回零,而不是標籤後面的實際數字。以下是我有:

public int extractVariables(String aLine) 
    { 
    Scanner scan = new Scanner(actualFile); 
    while(scan.hasNext()) 
    { 
     String line = scan.nextLine(); 
     if(line.contains("Columns in File:")) 
     { 
      StringBuilder numOfVariables = new StringBuilder(); 
      for(int i = 16; i < line.length(); i++) 
      { 
       numOfVariables.append(charAt(i)).trim(); 
      } 
     // check if the information is missing 
       if(numOfVariables != null && !numOfVariables.equals("")) 
       { 
        int variables = Integer.parseInt(numOfVariables); 
       } 
       else 
       { 
        System.out.print("Number of varibales is missing!"); 
       } 
      } 
      return variables; 
     } 
    } 

而且,我用命令行參數要求用戶輸入一個文件,並存儲文件到actualFile中,像這樣:

 try{ 
      File actualFile = new File(args[0]); 
      System.out.println("File was processed: true"); 
     } 
     catch (ArrayIndexOutOfBoundsException e) 
     { 
      System.out.println("File was processed: false. Re-enter filename."); 
      return; 
     } 

所以我把actualFile中的掃描儀打開文件並讀取行,掃描儀是否讀取正確的文件?也許這就是爲什麼該方法返回零?

回答

0

而不是做

for(int i = 16; i < line.length(); i++) 
     { 
      numOfVariables.append(charAt(i)).trim(); 
     } 

的看來,最好是使用nextInt的(); 因此,代碼將是這個樣子:

line.nextInt(); 

此外,爲了檢查是否有一個數字或如果缺少它,你可以使用:

if(line.hasNextInt()) {...} 
相關問題