1

I am working on a small project that takes user input (match results) on one line, splits the input and outputs the same data in a different format. I am struggling to find a way to output the data in a specific format. As well as total games played, I want my program to produce a chart like output in the format

home_name [home_score] | away_name [away_score]

This is the code I have at the minute which allows users to input results line after line in the following format

home_name : away_name : home_score : away_score

until they enter stop, which breaks the loop (and hopefully soon outputs the data).

import java.util.*;
public class results {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int totalGames = 0;
        String input = null;
        System.out.println("Please enter results in the following format"
                + " home_name : away_name : home_score : away_score"
                + ", or enter stop to quit");

        while (null != (input = scan.nextLine())){
            if ("stop".equals(input)){
                break;
            }
            String results[] = input.split(" : ");
            for (int x = 0; x < results.length; x++) {

            }       
        totalGames++;
        }
        System.out.println("Total games played is " + totalGames);  
    }
}
Morteza Asadi
  • 1,819
  • 2
  • 22
  • 39
  • As an aside, [Yoda conditions](https://en.wikipedia.org/wiki/Yoda_conditions) your while loop uses. Any reason for that? – Klitos Kyriacou Jan 05 '17 at 14:26
  • No specific reason, maybe just the style of teaching I have received. `while ((input = scan.nextLine()) != "stop")` seems to simplify things. – user7379397 Jan 05 '17 at 14:39
  • Don't compare strings using the `==` or `!=` operator. You need to use `equals` instead. For example, `while ((input = ...) != null && !input.equals("stop"))` – Klitos Kyriacou Jan 05 '17 at 14:45

4 Answers4

2

You can see here.

You can format your text as you wish.

The general syntax is %[arg_index$][flags][width][.precision]conversion char  Argument numbering starts with 1 (not 0). So to print the first argument, you should use 1$ (if you are using explicit ordering).

ddarellis
  • 3,912
  • 3
  • 25
  • 53
1

You can use regEx to parse the line:

(\w)\s(\w)\s|\s(\w)\s(\w)

Base on Java code from (from http://tutorials.jenkov.com/java-regex/matcher.html)

import java.util.regex.Pattern;
import java.util.regex.Matcher;

    public class MatcherFindStartEndExample{

        public static void main(String[] args){

            String text = "Belenenses 6 | Benfica 0";

            String patternString = "(\\w+)\\s(\\w+)\\s\\|\\s(\\w+)\\s(\\w+)";

            Pattern pattern = Pattern.compile(patternString);
            Matcher matcher = pattern.matcher(text);


            while (matcher.find()){
                    System.out.println("found: " + matcher.group(1));
                    System.out.println("found: " + matcher.group(2));
                    System.out.println("found: " + matcher.group(3));
                    System.out.println("found: " + matcher.group(4));
            }
        }}

Use this code instead of your

 String results[] = input.split(" : ");
            for (int x = 0; x < results.length; x++) {

            }
pringi
  • 3,987
  • 5
  • 35
  • 45
0

You can keep the games statistics by adding results array values to the finalResults ArrayList. And then outputting its results as stop input is entered.
For counting the total results per team HashMap<String, Integer> is the best choice.

Here is the complete code with comments to make it clear:

import java.util.*;

// following the naming conventions class name must start with a capital letter
public class Results {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int totalGames = 0;
        String input;
        System.out.println("Please enter results in the following format: \n"
                + "'HOME_NAME : AWAY_NAME : HOME_SCORE : AWAY_SCORE' \n"
                + "or enter 'stop' to quit");

        // HashMap to keep team name as a key and its total score as value
        Map<String, Integer> scoreMap = new HashMap<>();
        // ArrayList for storing game history
        List<String> finalResults = new ArrayList<>();
        // don't compare null to value. Read more http://stackoverflow.com/questions/6883646/obj-null-vs-null-obj
        while ((input = scan.nextLine()) != null) {
            if (input.equalsIgnoreCase("stop")) {   // 'Stop', 'STOP' and 'stop' are all OK
                scan.close(); // close Scanner object
                break;
            }
            String[] results = input.split(" : ");

            // add result as String.format. Read more https://examples.javacodegeeks.com/core-java/lang/string/java-string-format-example/
            finalResults.add(String.format("%s [%s] | %s [%s]", results[0], results[2], results[1], results[3]));

            // check if the map already contains the team
            // results[0] and results[1] are team names, results[2] and results[3] are their scores
            for (int i = 0; i < 2; i++) {
                // here is used the Ternary operator. Read more http://alvinalexander.com/java/edu/pj/pj010018
                scoreMap.put(results[i], !scoreMap.containsKey(results[i]) ?
                        Integer.valueOf(results[i + 2]) :
                        Integer.valueOf(scoreMap.get(results[i]) + Integer.valueOf(results[i + 2])));
            }
            totalGames++; // increment totalGames
        }

        System.out.printf("%nTotal games played: %d.%n", totalGames); // output the total played games

        // output the games statistics from ArrayList finalResults
        for (String finalResult : finalResults) {
            System.out.println(finalResult);
        }

        // output the score table from HashMap scoreMap
        System.out.println("\nScore table:");
        for (Map.Entry<String, Integer> score : scoreMap.entrySet()) {
            System.out.println(score.getKey() + " : " + score.getValue());
        }
    }
}

Now testing with input:

team1 : team2 : 1 : 0
team3 : team1 : 3 : 2
team3 : team2 : 2 : 2
sToP

The output is:

Total games played: 3.

team1 [1] | team2 [0]
team3 [3] | team1 [2]
team3 [2] | team2 [2]

Score table:
team3 : 5
team1 : 3
team2 : 2
DimaSan
  • 12,264
  • 11
  • 65
  • 75
  • Yes that format is perfect! However I am struggling to get my head around how I can output all results in that format after the loop has been broken, for example assuming the user has entered 3 lines of results, and then stop. This breaks the loop, only then would I like the data to be outputted in that format under one another – user7379397 Jan 05 '17 at 13:52
  • Whilst on the topic, any chance you could help me with another quick question? As well as displaying the total games played, I'd like to record total the total home score and total away score, how would I go about this? – user7379397 Jan 05 '17 at 16:02
  • `HashMap` is your best friend here. Look for my answer I updated it completely. Btw if you want to output teams by alphabetical order you can use [TreeMap](http://docs.oracle.com/javase/6/docs/api/java/util/TreeMap.html) or [LinkedHashMap](http://docs.oracle.com/javase/6/docs/api/java/util/LinkedHashMap.html) if you want to keep the put order. Hope it will help you. – DimaSan Jan 05 '17 at 18:58
0

You should do things in two times :

1) retrieving information entered by the user and storing it in instances of a custom class : PlayerResult.

2) performing the output according to the expected format. You should also compute the max size of each column before creating the graphical table.
Otherwise you could have a ugly rendering.

First step :

List<PlayerResult> playerResults = new ArrayList<PlayerResult>();

...
String[4] results = input.split(" : "); 
playerResults.add(new PlayerResult(results[0],results[1],results[2],results[3])

Second step :

// compute length of column
int[] lengthByColumn = computeLengthByColumn(results);
int lengthHomeColumn = lengthByColumn[0];
int lengthAwayColumn = lengthByColumn[1];

// render header
System.out.print(adjustLength("home_name [home_score]", lengthHomeColumn));
System.out.println(adjustLength("away_name [away_score]", lengthAwayColumn));

// render data
for (PlayerResult playerResult : playerResults){
   System.out.print(adjustLength(playerResult.getHomeName() + "[" + playerResult.getHomeName() + "]", lengthHomeColumn));
   System.out.println(adjustLength(playerResult.getAwayName() + "[" + playerResult.getAwayScore() + "]", lengthAwayColumn));
 }
davidxxx
  • 125,838
  • 23
  • 214
  • 215