将数据文件(包含字符串和int类型)存储到两个数组中(字符串数组,int数组)

时间:2018-02-17 00:11:58

标签: java

 package project1;

    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.Scanner;




    public class Project1 {


        public static void main(String[] args) throws FileNotFoundException{

            //Declaring arrays
            String [] teams = new String [50];
            int [] runs = new int [50];

            //calling class lastvalue where -1 is stored
            lastValue value = new lastValue();
            int count = value.value;

            //instantiating input file
               Scanner input = new Scanner(new File("C:\\Users\\andy_\\Documents\\NetBeansProjects\\project1\\baseballteams.txt"));


             //while loop
        while (input.hasNext()) {
            count++;
           find next line
            teams[count] = input.nextLine();
            runs[count] = input.nextInt();
          }

        //print all teams
        for(int i=0; i<=teams.length; i++){
            value.value ++;
                System.out.println("The teams are:" + teams[count] + "The Runs" + runs[count]);
        }



        }


    }

我想将团队名称存储到字符串数组中,然后运行到int数组中。但是,当我运行该程序时,它表示在控制台中抛出不匹配错误。 我还想显示球队名称

1 个答案:

答案 0 :(得分:0)

我自己没有看到文件,您的错误可能是由于缓冲错误造成的。当扫描器读取input.nextInt()时,它只读到0-9位的末尾,并且不包括之后的返回字符。在你的while循环尝试之后清除缓冲区如下:

while (input.hasNext()) {
    count++;
    teams[count] = input.nextLine();
    runs[count] = input.nextInt();
    input.nextLine(); //clearing buffer
}

Here's a reference.