2013-03-01 3 views
0

파일을 읽으려고하는데 그 이름 뒤에 숫자가 아닌 이름을 읽었습니다. 이 수를 문자열로 쓰지 말고 수레 또는 복식으로 만들어야합니다. 설상가상으로, 내가 읽어야하는 두 개의 숫자가 있습니다. 제발 도와주세요?Java의 파일에서 숫자를 읽는 방법은 무엇입니까?

내가 읽을 필요가 무엇의 예 (Btw는 코드에서 내가 필요한 물건을 가져온) :

McDonlad의 농장, 118.8 45,670

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

당신이 올바른 들여 쓰기를 사용하는 경우 읽기보다 쾌적한 될 것이라고 말했다 jlordo 것과 while' 고리? – jlordo

답변

1

을 모르겠어요 어떤 들어오는 O (

... 
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 모두 이중 원하는 포함해야합니다 파일은 다음을 수행 할 수있는 예 "118.8 45,670이 McDonlad의 농장,"주어진처럼 보이지만, r float) 값을 반환합니다.

일부 추가 참고 사항

: 떨어져 이미 코드가`당신 때문에 중복에, 당신은 첫 번째 줄을 건너 뛰는 알고 ...

관련 문제