简体   繁体   中英

How can I format the output with System.out?

I am creating a Premier League football table in my spare time and I have come across a problem. While the program runs I want it to be perfect and output in the format I want it to, the problem is:

  • You enter the the Input (" HomeTeam : AwayTeam : HomeScore : AwayScore ") as follows

  • When you are done with the list you enter "quit" to stop the program

  • My issue is that the scores come out like this (" HomeTeam | AwayTeam | HomeScore | AwayScore ")

  • I intend it to print like this (" HomeTeam [HomeScore] | AwayTeam [AwayScore] ")

I have tried many variations of System.out.printlns to no avail, even trying to make several Boolean conditions that will output the input in the way I want it too. I am truly at a loss and it is frustrating - I hope that someone can give me tips the code is attached

Edited for loop;

for (int i = 0; i < counter; i++) { // A loop
    String[] words = product_list[i].split(":"); 
    System.out.println(words[0].trim() + "[" + words[2].trim() + "]" + " | " + words[1].trim() + "[" + words[3].trim()) + "]";

This should work:

Scanner sc = new Scanner(System.in);

public void outputScore(String input) {

    String[] words = input.trim().split("\\s+");

    String satisfied = sc.nextLine();

    if (satisfied.equals("quit")) {
        System.out.println(words[0] + " [" + words[4] + "] | " + words[2] + " [" + words[6] + "]");
    }
}

This is what the method should look like when you call it:

outputScore(sc.nextLine());

Here is the code to your edited question:

String [] product_list = new String [100];
int counter = 0;

Scanner scanner = new Scanner(System.in);
System.out.println("Input as follows:");
System.out.println("Home team : Away team : Home score : Away score");

String line = null;

while (!(line = scanner.nextLine()).equals("")) {

    if (line.equals("quit")) {
           break;
    } else {
        product_list[counter] = line;

        System.out.println("Home team : Away team : Home score : Away score");
    }

    counter++;  
}

for (int i = 0; i < counter; i++) {
    String[] words = product_list[i].split(":");
    System.out.println(words[0].trim() + " : " + words[2].trim() + " | " + words[1].trim() + " : " + words[3].trim());
}

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM