0

ファイルを読み込もうとしていますが、名前は読み込めましたが、名前の後の数字は読み込めませんでした。これらの数値を String ではなく float または double にする必要があります。さらに悪いことに、読み取らなければならない数字が 2 つあります。助けてください。(ところで、必要なものをインポートしたコードで)

私が読まなければならないものの例:

マクドナルド ファーム、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
    }
}
...

dValues-Array には、必要な double (または float) 値がすべて含まれている必要があります。

いくつかの追加メモ: jlordo が既に言ったこととは別に、正しいインデントを使用すると、コードが読みやすくなります...

于 2013-03-01T20:59:19.327 に答える