Anyone that could help me with the java.util.Scanner class?
I can’t figure out exactly how to use the delimiter method.
Input: teamA-teamB 4-5
Output: teamA:teamB:4:-5
Expected output: teamA:teamB:4:5
Piece of my code:
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");
}
I would personally do this with a regex and group matching, but if you’re going to use a Scanner don’t focus on using delimiters, use the
hasNext(String)andnext(String)methods to match and retrieve the next pattern.Regex with grouping example: