gv555
gv555

Reputation: 19

How do I split user input from the console?

How do I split a line of user input into separate strings and store, for example, if the input format was as follows (for a results chart)..

home_name : away_name : home_score : away_score

How would I go about splitting the input into 4 different parts and storing separately? (User will be prompted to input in the above format only, and I'm using a while loop to continue to ask for line results until user enters stop).

Upvotes: 1

Views: 563

Answers (3)

ninja.coder
ninja.coder

Reputation: 9648

If the format of your input data is consistent then you can simply use a pattern like : and do the following:

public static void main(String[] args) {
    /* Scan Inputs */
    Scanner in = new Scanner(System.in);

    /* Input String */
    String input = null;

    /* Create StringBuilder Object */
    StringBuilder builder = new StringBuilder();

    String[] headers = { "home_name: ", "away_name: ", "home_score: ",
            "away_score: " };
    while (null != (input = in.nextLine())) {
        /* Break if user enters stop */
        if ("stop".equalsIgnoreCase(input)) {
            break;
        }

        /* Trim the first and the last character from input string */
        input = input.substring(1, input.length() - 1);

        /* Split the input string using the required pattern */
        String tokens[] = input.split(" : ");

        /* Print the tokens array consisting the result */
        for (int x = 0; x < tokens.length; x++) {
            builder.append(headers[x]).append(tokens[x]).append(" | ");
        }
        builder.append("\n");
    }

    /* Print Results & Close Scanner */
    System.out.println(builder.toString());
    in.close();
}

Note that here I have used substring() function to get rid of < and > in the starting and ending of the input string before splitting it using the given pattern.

Input:

<manchester united : chelsea : 3 : 2>
<foobar : foo : 5 : 3>
stop

Output:

home_name: manchester united | away_name: chelsea | home_score: 3 | away_score: 2 | 
home_name: foobar | away_name: foo | home_score: 5 | away_score: 3 | 

Upvotes: 4

Chai T. Rex
Chai T. Rex

Reputation: 3018

If the format is exactly as you've described, a fairly efficient way to parse it is this:

public static void main(String[] args) {
    String line = "<Raptors : T-Rexes : 5 : 10>";

    final int colonPosition1 = line.indexOf(':');
    final int colonPosition2 = line.indexOf(':', colonPosition1 + 1);
    final int colonPosition3 = line.indexOf(':', colonPosition2 + 1);

    final String homeName = line.substring(1, colonPosition1 - 1);
    final String awayName = line.substring(colonPosition1 + 2, colonPosition2 - 1);
    final int homeScore = Integer.parseInt(line.substring(colonPosition2 + 2, colonPosition3 - 1));
    final int awayScore = Integer.parseInt(line.substring(colonPosition3 + 2, line.length() - 1));

    System.out.printf("%s: %d vs %s: %d\n", homeName, homeScore, awayName, awayScore);
}

Upvotes: 0

Alex Javarotti
Alex Javarotti

Reputation: 116

In some cases, the input could be a little 'inconsistent': blanks not provided or changes produced by new versions. If is the case, it is possible apply some protection with regular expressions.

public static void main(String[] args) {

    boolean validInput = false; 

    String input = "<home_name : away_name : home_score : away_score>";

    String pattern = "<.*:.*:.*:.*>";
    Pattern r = Pattern.compile(pattern);
    Matcher m = r.matcher(input);
    validInput = m.matches();

    if(validInput) {
        input = input.substring(1, input.length() - 1);
        String tokens[] = input.split("\\s*:\\s*");

        for (int x = 0; x < tokens.length; x++) {
            System.out.println(tokens[x]);
        }

    } else {
        System.out.println("Input is invalid");
    }
}

Upvotes: 1

Related Questions