0

I'm reading in two lines of a .txt file (ui.UIAuxiliaryMethods; is used for this) to calculate the BodyMassIndex(BMI) of patients, but I get a inputmismatchexception when the patientLenght is reached. These are my two lines of input, seperated by a \t:

Daan Jansen M   1.78    83
Sophie Mulder   V   1.69    60

It's sorted in Name - Sex - Length - Weight. This is my code to save all elements in strings, doubles and integers:

package practicum5;

import java.util.Scanner;
import java.io.PrintStream;
import ui.UIAuxiliaryMethods;

public class BodyMassIndex {

    PrintStream out;

    BodyMassIndex() {
        out = new PrintStream(System.out);
        UIAuxiliaryMethods.askUserForInput();
    }

    void start() {
        Scanner in = new Scanner(System.in);

        while(in.hasNext()) {
            String lineDevider = in.nextLine(); //Saves each line in a string

            Scanner lineScanner = new Scanner(lineDevider);

            lineScanner.useDelimiter("\t");
            while(lineScanner.hasNext()) {
                String patientNames = lineScanner.next();
                String patientSex = lineScanner.next();
                double patientLength = lineScanner.nextDouble();
                int patientWeight = lineScanner.nextInt();
            }   
        }   
        in.close();
    }
    public static void main(String[] args) {
        new BodyMassIndex().start();
    }
}

Somebody got a solution for this?

  • **Related Question:** [Scanner issue when using nextLine after nextInt](http://stackoverflow.com/questions/7056749/scanner-issue-when-using-nextline-after-nextint) – Eng.Fouad Nov 28 '12 at 15:39

3 Answers3

2

Your name has two tokens not one, so lineScanner.next() will only get the token for the first name.

Since a name can have more than 2 tokens theoretically, consider using String.split(...) instead and then parsing the last two tokens as numbers, double and int respectively, the third from last token for sex, and the remaining tokens for the name.

One other problem is that you're not closing your lineScanner object when you're done using it, and so if you continue to use this object, don't forget to release its resource when done.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
0

Your name field has two token. and you are trying to treat them as one. that;s creating the problem. You may use a " (double quote) to separate the name value from others. String tokenizer may do your work.

Debobroto Das
  • 834
  • 6
  • 16
  • In debug modus the whole name is saved correctly into the string patientName, just as the patientSex. – Erik de Jong Nov 28 '12 at 15:59
  • your sample input seems to have some problem. in your code you used tab as delimiter. but your input seems to use a space as delimiter between name and sex (in the first line). – Debobroto Das Nov 28 '12 at 16:05
0

I changed the dots to commas in the input file. Hooray.