0

I am trying to read a text file that says:

Cycle [numberOfWheels=4.0, weight=1500.0]

the code runs correctly but it doesn't recognize the doubles. the output is: 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());
      } 
     }
Chiseled
  • 2,280
  • 8
  • 33
  • 59
user3764862
  • 25
  • 1
  • 2
  • 9

2 Answers2

0

Scanner, by default, uses whitespace as a delimiter. Since your file has no whitespace between the numbers, it reads [numberOfWheels=4.0,, instead of just 4.0.

Just use Scanner.next() to get the whole line, and use substring to get the individual numbers.

Tetramputechture
  • 2,911
  • 2
  • 33
  • 48
0

You should parse complex input manually e.g. by lexical parser (antlr) or with regexp:

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))
        );
    }
}
ursa
  • 4,404
  • 1
  • 24
  • 38