2013-03-01 223 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已经说了,你的代码将变得更愉快,如果你使用正确的缩进阅读...