Scanner NextInt()使用逗号分隔的坐标

时间:2014-02-07 08:16:39

标签: java io

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

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()并打印出s2.nextInt(),它返回1.但我不确定我在使用Scanner做错0和1设置为两个不同的变量。谢谢你的帮助!

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

3 个答案:

答案 0 :(得分:3)

问题是Scanner#nextInt()返回一个数值(确切地说:int类型的值),您尝试将其赋值给String变量。

所以而不是:

String xCoord = s2.nextInt();
String yCoord = s2.nextInt();

尝试:

int x = s2.nextInt();
int y = s2.nextInt();

答案 1 :(得分:1)

您可以使用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());
   }

答案 2 :(得分:1)

试试这个

    sc.useDelimiter("\\D+");
    int n1 = sc.nextInt();
    int n2 = sc.nextInt();