如何以特定布局输出到控制台?

时间:2017-01-05 13:35:59

标签: java

我正在开发一个小项目,它将用户输入(匹配结果)放在一行上,拆分输入并以不同的格式输出相同的数据。我正在努力寻找一种以特定格式输出数据的方法。除了玩的总游戏外,我希望我的程序能够以

格式生成类似输出的图表
home_name [home_score] | away_name [away_score]

这是我现在的代码,它允许用户以下列格式逐行输入结果

home_name : away_name : home_score : away_score

直到他们进入stop,这会打破循环(并希望很快输出数据)。

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);  
    }
}

4 个答案:

答案 0 :(得分:2)

您可以看到here

您可以根据需要设置文本格式。

  

一般语法是   %[arg_index $] [flags] [width] [.precision]转换char参数   编号从1开始(不是0)。所以要打印第一个参数,你   应该使用1 $(如果您使用显式排序)。

答案 1 :(得分:1)

您可以使用regEx来解析该行:

(\ w)的\ S(\ w)的\ S | \ S(\ w)的\ S(\ w)的

基于来自(来自http://tutorials.jenkov.com/java-regex/matcher.html

的Java代码
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));
            }
        }}

使用此代码代替

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

            }

答案 2 :(得分:0)

您可以通过将results数组值添加到finalResults ArrayList来保留游戏统计信息。然后输入结果stop输入。
对于计算每个团队HashMap<String, Integer>的总结果是最佳选择。

以下是包含注释的完整代码:

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());
        }
    }
}

现在使用输入进行测试:

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

输出结果为:

Total games played: 3.

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

Score table:
team3 : 5
team1 : 3
team2 : 2

答案 3 :(得分:0)

你应该做两次事情:

1)检索用户输入的信息并将其存储在自定义类的实例中:PlayerResult

2)根据预期格式执行输出。您还应该在创建图形表之前计算每列的最大大小 否则你可能会有一个难看的渲染。

第一步:

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

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

第二步:

// 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));
 }