首页 > 解决方案 > 如何解析具有多种数据类型的代码行

问题描述

目前正在开发一个程序,该程序读取足球运动员的统计数据并将数据转换为二进制并将其全部写入文件。我遇到的问题是解析我正在读取的文件包含的所有不同数据类型。我正在阅读的文件将具有以下格式 - lastName yearsExp position height weight 40ydSpeed team active? 文件如下所示: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

标签: javaexceptionfile-iobinary

解决方案


如何解析不同的数据类型,int、char、double、String 和 boolean

为了:

int x = Integer.parseInt(s)
char x = s.charAt(0)
double x = Double.parseDouble(s)
String x = s
boolean x = Boolean.parseBoolean(s)

推荐阅读