我正在尝试以以下格式解析文本文件中的信息:

WarningGeotask: 0, 1


第一个单词是某个特定对象的关键字,该关键字要在紧随其后的数字指定的坐标位置上创建。这是我的循环当前的样子:

// Open file and scan for a line
File f = new File("Simulation.Configuration");
Scanner s = new Scanner(f);

while (s.hasNextLine()) {
    // Parse each line with a temporary scanner
    String line = s.nextLine();
    Scanner s2 = new Scanner(line);

    // Get keywords from the file to match to variable names
    String keyword = s2.next();

    //...Multiple if statements searching for different keywords...

    else if (keyword.equals("WarningGeotask:")) {
        int xCoord = s2.nextInt();
        int yCoord = s2.nextInt();

        WarningGeotask warningGeotask = new WarningGeotask(xCoord, yCoord);

        s2.close();
        continue;
    }
}


但是,此代码无法正常工作。实际上,String xCoord = s2.nextInt()会引发错误。我可以执行s2.next()并打印出返回1的s2.nextInt()。但是,我不确定用Scanner将0和1设置为两个不同的变量时我做错了什么。谢谢您的帮助!

编辑:字符串变量xCoord和yCoord应该是int-我的错。

最佳答案

您可以使用split()

当您阅读这些行时,将其设置为逗号分隔值:

while (s.hasNextLine()) {
   String line = s.nextLine().replace(":",",");
   String[] data =line.split(",");
   //...Multiple if statements searching for different keywords
   else if(data[0].equals("WarningGeotask:")){
      WarningGeotask warningGeotask = new WarningGeotask(Integer.parseInt(data[1].trim()), Integer.parseInt[data[2].trim());
   }

关于java - 扫描仪NextInt()使用逗号分隔的坐标,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21622567/

10-10 22:10