如何解析具有多种数据类型的代码行

目前正在开发一个程序,该程序读取足球运动员的统计数据并将数据转换为二进制并将其全部写入文件。我遇到的问题是解析我正在读取的文件包含的所有不同数据类型。我正在读取的文件将采用以下格式 - 姓氏 年数 职位 身高 体重 40ydSpeed 团队活跃吗?文件的示例如下: Brady, 14, QB, 1, 210, 4.9, Patriots, true 我想知道如何解析不同的数据类型,int,char,double,String和布尔值。


到目前为止,我的程序要求用户输入一个文件,它会捕获无效文件中的任何 FileNotFoundExceptions 并循环,直到输入有效文件。然后程序读取该文件并将其全部存储到一个列表中。


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

     File file;

     Scanner inputFile;

     Scanner readFile;

     String line;

     String fileName;

     int x = 1;


     ArrayList<String> stats = new ArrayList<String>();


    do {

        Scanner kb = new Scanner(System.in);

        System.out.println("Please enter the name of a " +

                "file containing football player data:");

        fileName = kb.nextLine();


        try {

            file = new File(fileName);

            inputFile = new Scanner(file);

            while(inputFile.hasNext()) {


                    stats.add(inputFile.nextLine());

            }

            x=2;


        }

        catch (FileNotFoundException e)

            {

            System.out.print("File not found. ");

            }

       }

    while(x==1);


    for (String s : stats) {

        System.out.println(s);

    }


    // TODO use the following methods for writing to binary

    // TODO writeUTF, writeInt, writeChar, writeInt, writeInt, writeDbl, writeByte


慕姐8265434
浏览 88回答 3
3回答

慕后森

如何解析不同的数据类型:int、char、double、String 和 boolean为了:int x = Integer.parseInt(s)char x = s.charAt(0)double x = Double.parseDouble(s)String x = sboolean x = Boolean.parseBoolean(s)

精慕HU

当前的问题是 thaArrayList<String> stats = new ArrayList<String>();强制您读取的任何值都是String。如果您了解了类,那么您可以创建一个模拟足球运动员的类:让我们以它FootballPlayer为例。您将FootballPlayer拥有许多不同类型的字段。你会有一个表示lastNameis a&nbsp;String、yearsExpthat is anint等等。然后,这里:&nbsp;while(inputFile.hasNext())&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;stats.add(inputFile.nextLine()); &nbsp;}您可以保留与您要读取的字段相对应的索引。lastName可以对应于index0、1yearsExpr等。然后,根据索引值(您可以使用语句),您可以调用返回适当类型switch的不同方法,例如,如果索引为 1 (for&nbsp;)。调用此适当的方法后,您可以将返回值分配给 实例中的相应字段。ScannernextInt()yearsExprFootballPlayer将来,整个过程可以通过使用库来解析您正在使用的数据格式来为您处理,例如 CSV 解析器(因为看起来数据是用逗号分隔的)。

青春有我

您可以用 或任何其他常用分隔符分隔输入,,然后尝试一一解析。String input = "Tom, 15, 6, 86.4"; // name, age, grade, markString[] inputs = input.split(", "); // [ Tom, 15, 6, 86.4 ]for (String in : inputs) {&nbsp; &nbsp; if (isInteger(in)) {&nbsp; &nbsp; &nbsp; &nbsp; // something&nbsp; &nbsp; } else if (isString(in)) {&nbsp; &nbsp; &nbsp; &nbsp; // other thing&nbsp; &nbsp; } // etc}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java