1

任何可以帮助我处理 java.util.Scanner 类的人吗?
我无法弄清楚如何使用分隔符方法。

输入:teamA-teamB 4-5

输出:团队A:团队B:4:-5

预期输出:teamA:teamB:4:5

我的一段代码:

public void readResult()
{
    String team1, team2;
    int goals1, goals2;
    Scanner scanner = new Scanner(System.in);
    scanner.useDelimiter("\\s*-\\s*");
    if (scanner.hasNext())
    {
        team1 = scanner.next();
        scanner.useDelimiter("\\d*-\\d*");
        if(scanner.hasNext())
        {
            team2 = scanner.next().trim();
            scanner.useDelimiter("-");
            if(scanner.hasNext())
            {
                goals1 = scanner.nextInt();
                scanner.useDelimiter("\\n");
                if(scanner.hasNext())
                {
                    goals2 = scanner.nextInt();
                    System.out.println(team1 + ":" +  team2 + ":" + goals1 + ":" + goals2);
                    scanner.close();
                    return;
                }
            }
        }
    }
    scanner.close();
    System.out.println("bad format");
}
4

1 回答 1

0

我个人会使用正则表达式和组匹配来执行此操作,但如果您要使用扫描仪,请不要专注于使用分隔符,使用hasNext(String)andnext(String)方法来匹配和检索下一个模式。

带有分组示例的正则表达式:

    String input  ="teamA-teamB 4-5";
    String team1, team2;
    int goals1, goals2;

    Matcher matcher = 
        Pattern.compile("(.*?)\\s*-\\s*(.*?)\\s*(\\d*)\\s*-\\s*(\\d*)")
        .matcher(input);
    if ( matcher.matches() ) {
        team1 = matcher.group(1);
        team2 = matcher.group(2);
        goals1 = Integer.parseInt(matcher.group(3));
        goals2  = Integer.parseInt(matcher.group(4));
        System.out.println(team1 + ":" +  team2 + ":" + goals1 + ":" + goals2);
    }
于 2010-09-10T19:52:21.993 回答