运行后键入不匹配

时间:2014-03-04 14:10:39

标签: java type-mismatch mismatch

package skater;

import java.io.*;
import java.util.*;

public class TestSkater 
{
    public static void main(String[]args) throws IOException
    {
        Scanner sc = new Scanner(new File("C:/pairs.txt"));
        String name1 = null, name2 = null, Country = null;
        double [] Technical = new double [8];
        double [] Performance = new double[8];

        try {  
            while(sc.hasNext())
            {
                name1=sc.nextLine();
                name2 = sc.nextLine();
                Country = sc.nextLine();

                for (int t = 0; t<Technical.length; t++)
                {
                    Technical[t] = sc.nextDouble();
                }
                for(int y = 0; y<Performance.length; y++)
                {
                    Performance[y] = sc.nextDouble();
                }
                // Skater [] skaters = new Skater[20];
                Skater S1 = new Skater(name1,name2,Country,Technical,Performance);
                System.out.println(S1);
                sc.nextLine();
            }   
        }
        catch(Exception e)
        {
            System.out.println(e.getMessage());
            System.out.print("Bad program");
        }
    }
}

每当我在没有try和catch的情况下运行我的代码时,我得到一个InputMismatchException。它是从一个文件中读取的,该文件包含所有团队名称及其分数和国家/地区。它的格式如下:

smith

jones

australia

4.2 5.1 3.8 2.9 5.0 4.6 4.9 4.3

4.9 4.8 5.8 3.8 4.9 4.6 5.0 4.5

lennon

murray

england

2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8

3.1 3.2 3.3 3.4 3.5 3.6 3.7 3.8

我知道nextLine()告诉它查看下一行数据,以及我用于数组nextDouble()Performance的{​​{1}},告诉它要看下一个双排。

我无法弄清楚为什么它会给我这个错误。我认为这是因为当它移动到下一个团队的第一个名字时,它仍然将其视为数组Technical中的双精度,但我无法弄清楚如何解决该问题。

1 个答案:

答案 0 :(得分:0)

如果不知道扫描仪的功能(nextLine,nextDouble)是什么以及您所读取的文件的确切格式,很难确定。

假设:
nextLine 将文字读取到行尾 nextDouble 读取并解析文本到下一个中​​断/空格
然后,按照您阅读输入的方式,我假设它的格式为:

Name1
Name2
Country
0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0
0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0

如果假设是正确的并且不是输入的格式那么就是你的问题。

如果你确定nextLine文本条目被正确读取,那么一个选项可能是将该行读作字符串,拆分空格(或逗号,或分号或任何分隔它们)并自己解析它们,例如

string[] tmp = sc.nextLine().split(' ');
for(int t = 0; t<Technical.length; t++)
    Technical[t] = Double.parseDouble(tmp[t]);
相关问题