Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何以特定布局输出到控制台?_Java - Fatal编程技术网

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

Java 如何以特定布局输出到控制台?,java,Java,我正在做一个小项目,它将用户输入(匹配结果)放在一行上,分割输入并以不同的格式输出相同的数据。我正在努力寻找一种以特定格式输出数据的方法。除了玩的总游戏数,我希望我的程序以以下格式生成类似图表的输出 home_name [home_score] | away_name [away_score] 这是我目前拥有的代码,它允许用户以以下格式逐行输入结果 home_name : away_name : home_score : away_score 直到他们进入停止,这打破了循环(并希望很快输出数

我正在做一个小项目,它将用户输入(匹配结果)放在一行上,分割输入并以不同的格式输出相同的数据。我正在努力寻找一种以特定格式输出数据的方法。除了玩的总游戏数,我希望我的程序以以下格式生成类似图表的输出

home_name [home_score] | away_name [away_score]
这是我目前拥有的代码,它允许用户以以下格式逐行输入结果

home_name : away_name : home_score : away_score
直到他们进入停止,这打破了循环(并希望很快输出数据)

import java.util.*;
公开课成绩{
公共静态void main(字符串[]args){
扫描仪扫描=新扫描仪(System.in);
整数totalGames=0;
字符串输入=null;
System.out.println(“请按以下格式输入结果”
+“主场比赛名称:客场比赛名称:主场比赛得分:客场比赛得分”
+“,或输入stop以退出”);
while(null!=(input=scan.nextLine()){
如果(“停止”。等于(输入)){
打破
}
字符串结果[]=input.split(“:”);
对于(int x=0;x
您可以看到

您可以根据需要格式化文本

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


您可以通过将
结果
数组值添加到
finalResults
ArrayList来保存游戏统计信息。然后将其结果输出为输入的
stop
input。
计算每个团队的总结果时,
HashMap
是最佳选择

以下是完整的代码和注释,以明确说明:

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());
        }
    }
}
输出为:

Total games played: 3.

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

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

您可以使用regEx解析该行:

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

基于Java代码from(from)

使用此代码而不是您的

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

            }
String results[]=input.split(“:”);
对于(int x=0;x
你应该分两次做事:

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])

是的,这种格式很完美!然而,我正在努力弄清楚,在循环被破坏后,我如何能够以这种格式输出所有结果,例如,假设用户输入了3行结果,然后停止。这打破了循环,只有这样我才会希望数据以这种格式一个接一个地输出。在这个话题上,你能帮我回答另一个快速问题吗?除了显示比赛总数,我还想记录主场和客场的总比分,我该怎么做?
HashMap
是您最好的朋友。寻找我的答案,我完全更新了它。顺便说一句,如果你想按字母顺序输出团队,你可以使用,或者如果你想保持放置顺序。希望它能对您有所帮助。顺便说一句,您的while循环使用。有什么原因吗?没有具体的原因,也许只是我所接受的教学方式<代码>while((input=scan.nextLine())!=“stop”)
似乎可以简化事情。不要使用
=
来比较字符串=操作员。您需要使用
等于
。例如,
while((input=…)!=null&&!input.equals(“stop”))
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++) {

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