Michael Michael - 1 year ago 45
Java Question

Is it possible to create a single, long String of names from a for loop? (No lists/arrays)

System.out.println("How many teams are in this tournament?");

for(int x=1; x<=no_of_teams; x+=1)
System.out.println("Please enter the name of team " + x);

I would like to have team contain all the user inputs, so I can then use String.split later on in the program to output the team names once again.

I asked my original question on Reddit but to no avail, it went like this:

We have been asked to create a program which runs to collect data
based on a round robin soccer tournament for 'n' no. of teams. My
issue is when I must ask for all the team names at the beginning
(which I must) based on what no. of teams the user inputs of course, I
can do this with a for loop and the output is perfect:

input the code from up above here

However, as I am sure you are aware, this
basically means that team will now just be stored as whichever team
name was entered last as the for loop caused it to be overwritten.
This is a problem because later down in the program you are meant to
then output all the different team names for when they are playing
against each other but team is only storing one team name. Using
team1, team2, team3, etc. is impractical because the user can enter an
infinite amount for the number of teams. We are not allowed to use
arrays because we have not covered them yet, and by all accounts the
way I am to get around this is to use String concatenation and while
loops, but I am unsure how this would apply. Any help would be
gratefully appreciated! Thanks.

Answer Source

You can just append names to a String with an attached delimiter:

StringBuilder team = new StringBuilder();
for(int x=1; x<=no_of_teams; x+=1)
    System.out.println("Please enter the name of team " + x);
    //this will add a - after each name, and then you could split on the - character

However, this is really not the best options. I would use an array to store names. The answer I gave t would return one big string, that you would have to split on the '-'.

After you got your string, you could split it by doing:


If you wanted to output all the team names you would do something like:

for(String aTeam :  team.toString().split("-")){
   System.out.println("Team Name: " + aTeam);