0

( ANSWER: in the switch case I forgot my break statements and I guess that was throwing the Scanner off! )

I'm writing a program to read a file that contains three kinds of shapes, followed by their corresponding dimension and write them into an object array. Circles list their radius, Squares their edgelength, but for Triangles their base and height! I wrote what was is logical to me, but my code throws InputMismatchException errors and I'm having trouble finding where I'm going wrong.

The file that the scanner reads is straightforward, A string, followed by 1 or (if the string is a triangle) 2 doubles. I figured I'd create a variable for the triangle's height, and under the condition that the string is a Triangle, it should read another double into that variable. But it throws a mismatchException?

for (int i = 0; fs.hasNext(); i++) {
  String word = fs.next();
  double field = fs.nextDouble();
  double triangleH = 0.0;
  switch (word) {
  case circle:
    shape[i] = new Circle(field);
  case square:
    shape[i] = new Square(field);
  case triangle:
    triangleH = fs.nextDouble();
    //^^^line where the error is thrown 
    shape[i] = new IsoscelesTriangle(field, triangleH);
  }
}

this is a sample of the file 'fs' is reading.

triangle 385.64 796.55
circle 455.71
triangle 697.73 261.17
circle 273.11
triangle 1051.95 879.48
triangle 425.96 772.16
square 864.19

the IsoscelesTriangle class looks like this

public class IsoscelesTriangle implements Shape {
  private double base = 0.0;
  private double height = 0.0;
  private double area = 0.0;

  public IsoscelesTriangle(double b, double h) {
    setBase(b);
    setHeight(h);
    setArea(b, h);
  }
  //more methods
}
Evan Jones
  • 43
  • 7

2 Answers2

0

I don't see any error in your code, may be in your file on a part that was not posted here there is not a float value next to the triangle

double nextDouble()

Returns the next token as a long. If the next token is not a float or is out of range, InputMismatchException is thrown.

Please cry catching the Exception print it to see more insights.

Jeeppp
  • 1,553
  • 3
  • 17
  • 39
0

Your problem is the input file. I removed dots and used commas and everything run fine. Try this input:

triangle 385,64 796,55
circle 455,71
triangle 697,73 261,17
circle 273,11
triangle 1051,95 879,48
triangle 425,96 772,16
square 864,19
Apostolis I.
  • 112
  • 6