0

我正在尝试读入一个文件,并且我设法读入了名称,但没有读入名称后面的数字。我需要将这些数字不是字符串,而是浮点数或双精度数。更糟糕的是,我必须读入两个数字。请帮忙?(顺便说一句,在代码中我已经导入了必要的东西)

我必须阅读的一个例子:

麦当劳农场 , 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);
              }
 }
  }
}
}
4

1 回答 1

1

我不知道您传入的文件是什么样的,但以“McDonlad's Farm , 118.8 45670”为例,您可以执行以下操作:

...
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
    }
}
...

-ArraydValues应包含所有所需的双精度(或浮点)值。

一些额外的注意事项:除了 jlordo 已经说过的,如果你使用正确的缩进,你的代码会变得更容易阅读......

于 2013-03-01T20:59:19.327 回答