2014-10-29 66 views
0

我想讀的文本文件,上面寫着:輸入匹配異常雙

Cycle [numberOfWheels=4.0, weight=1500.0] 

代碼正常運行,但它不承認雙打。 的輸出是:Cycle [numberOfWheels= 0.0, weight= 0.0]

  import java.io.File; 
      import java.io.FileNotFoundException; 
      import java.util.Scanner; 

      public class Cycle { 
      public static double numberOfWheels; 
      public static double weight; 

      public Cycle(double numberOfWheels, double weight) 
      { 
      this.numberOfWheels=numberOfWheels; 
      this.weight=weight; 
      } 

      @Override 
      public String toString() { 
      return "Cycle [numberOfWheels= " + numberOfWheels + ", weight= " + weight 
      + "]"; 
      } 

      public static void main(String[] args) throws FileNotFoundException 
      { 
      // TODO Auto-generated method stub 

      File text = new File("C:/Users/My/workspace/CycleOutput/Cycle.txt"); 

      try { 

       Scanner sc = new Scanner(text); 

       while (sc.hasNextDouble()) 
       { 
       numberOfWheels=sc.nextDouble(); 
       } 

       while (sc.hasNextDouble()) 
       { 
       sc.next(); 
       } 
       } 
      catch (FileNotFoundException e) { 
       e.printStackTrace(); 
      } 

      Cycle cycle1=new Cycle(numberOfWheels, weight); 
      System.out.println(cycle1.toString()); 
     } 
    } 

回答

0

Scanner默認情況下,使用空格作爲分隔符。由於您的文件在數字之間沒有空白,因此它將顯示[numberOfWheels=4.0,,而不僅僅是4.0

只需使用Scanner.next()即可獲取整行,並使用substring獲取單個數字。

0

您應該手動解析複雜輸入,例如通過詞法分析器(antlr)或正則表達式:

Scanner sc = new Scanner(new StringReader("Cycle [numberOfWheels=4.0, weight=1500.0]\n")); 
Pattern pattern = Pattern.compile("Cycle\\s*\\[numberOfWheels=(.*),\\s*weight=(.*)\\]"); 
while (sc.hasNextLine()) { 
    Matcher matcher = pattern.matcher(sc.nextLine()); 
    if (matcher.matches()) { 
     return new Circle(
      Double.parseDouble(matcher.group(1)), 
      Double.parseDouble(matcher.group(2)) 
     ); 
    } 
}