2013-03-01 45 views
0

我想讀取一個文件,我已經設法讀取名稱後面的數字,但不讀取名稱後面的數字。我需要讓這些數字不是進入字符串,而是進入浮動或雙打。更糟糕的是,有兩個數字我必須閱讀。幫助請嗎? (順便說一下在我的代碼導入了必要的東西)如何從Java中的文件中讀取數字?

什麼我要讀的一個例子:

McDonlad的農場,118.8 45670

public class Popcorn{ 


public static void main (String [] args) throws IOException { 


      System.out.println("Enter the name of the file"); 
      Scanner in = new Scanner(System.in); 
      String filename = in.next(); 
      Scanner infile = new Scanner(new FileReader(filename)); // 
      String line = "" ; 

      //to get stuff from the file reader 

      while (infile.hasNextLine()) 
      { line= infile.nextLine(); 

      // int endingIndex =line.indexOf(','); 
      // String fromName = line.substring(0, endingIndex); //this is to get the name of the farm 
      // if (fromName.length()>0){ 
      // System.out.println (fromName); 
      // } 
      // else if (fromName.length()<= 0) 
      // System.out.println(""); some of the durdling that goes on 
      // } 
      while (infile.hasNextLine()) 
      { 
      line= infile.nextLine().trim(); // added the call to trim to remove whitespace 
       if(line.length() > 0) // test to verify the line isn't blank 
       { 
       int endingIndex =line.indexOf(','); 
       String fromName = line.substring(0, endingIndex); 
       String rest = line.substring(endingIndex + 1); 
       // float numbers = Float.valueOf(rest.trim()).floatValue(); 
    Scanner inLine = new Scanner(rest); 

       System.out.println(fromName); 
       } 
} 
    } 
} 
} 
+1

你知道你是跳過第一線,由於重複'while'循環? – jlordo 2013-03-01 12:56:29

回答

1

我不知道你的到來文件的樣子,但鑑於你可以做下面的示例中的「118.8 45670 McDonlad的農場」:

... 
String rest = line.substring(endingIndex + 1); 
String[] sValues = rest.split("[ \t]"); // split on all spaces and tabs 
double[] dValues = new double[sValues.length]; 
for(int i = 0; i < sValues.length; i++) { 
    try { 
     dValues[i] = Double.parseDouble(sValues[i]); 
    } catch (NumberFormatException e) { 
     // some optional exceptionhandling if it's not 
     // guaranteed that all last fields contain doubles 
    } 
} 
... 

dValues - 陣列應該包含所有所需的雙(鄰r浮點)值。

一些其他注意事項:除了什麼jlordo已經說了,你的代碼將變得更愉快,如果你使用正確的縮進閱讀...