0

我正在读取两行 .txt 文件(ui.UIAuxiliaryMethods; 用于此)来计算患者的 BodyMassIndex(BMI),但是当达到 patientLenght 时,我得到一个 inputmismatchexception。这是我的两行输入,由 \t 分隔:

Daan Jansen M   1.78    83
Sophie Mulder   V   1.69    60

它按名称 - 性别 - 长度 - 重量排序。这是我将所有元素保存在字符串、双精度和整数中的代码:

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();
    }
}

有人对此有解决方案吗?

4

3 回答 3

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.

于 2012-11-28T15:37:26.787 回答
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.

于 2012-11-28T15:41:09.657 回答
0

我将输入文件中的点更改为逗号。万岁。

于 2012-11-30T12:49:59.813 回答