1

I have a homework question that wants me to write a

Program that takes three names and their scores from a user by using delimiters. Example:

Tom:54, Matt:12, Ali:89

I keep getting an input mismatch exception when Java is assigning user2Score. I am currently testing my program but scanner seems to take in user2 as " Matt" instead of "Matt". I'm not sure if my delimiter syntax is correct. Any feedback would be greatly appreciated!

import java.util.Scanner;

public class General {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in).useDelimiter("[: | ,*\\s]");

        String user1;
        String user2;
        String user3;

        int user1Score;
        int user2Score;
        int user3Score;

        System.out.println("Please enter the user name and their score:");
        user1 = input.next();
        user1Score = input.nextInt();
        user2 = input.next();
        user2Score = input.nextInt();
        user3 = input.next();
        user3Score = input.nextInt();


        System.out.println(user1 + " " + user1Score + "\n" + user2 + " " + user2Score);
    }

}
Toby Speight
  • 27,591
  • 48
  • 66
  • 103

1 Answers1

2

you can use the trim()-method of String. This elimates all spaces at the beginning and at the end of the string.

Markus
  • 1,141
  • 1
  • 9
  • 25
  • If your input variable is taking one string like "Tom:54, Matt:12, Ali:89", then trim() wouldn't work because it only removes white space at the beginning and end of the string. Instead, replaceAll("\\s+","") might work per this question: http://stackoverflow.com/questions/15633228/how-to-remove-all-white-spaces-in-java – jones-chris Mar 21 '17 at 15:30
  • I tried adding the .trim() to user2 = input.next() but it still did not work? – Matthew LaFayette Mar 21 '17 at 15:31
  • I also tried changing user2 = input.next().replaceAll("\\s+",""); but It didn't seem to work – Matthew LaFayette Mar 21 '17 at 15:44