可以帮助我使用java.util.Scanner类的人吗?我无法确切地知道如何使用定界符方法。
输入:teamA-teamB 4-5
输出:teamA:teamB: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");
}
我个人将使用正则表达式和组匹配进行此操作,但是如果您要使用扫描仪,则不要专注于使用分隔符,请使用hasNext(String)
和next(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);
}