• Post Reply Bookmark Topic Watch Topic
  • New Topic

Using String Split and Arrays  RSS feed

 
Bella Hill
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, I am working on a project for university but am new to Java, and I'm totally stuck.

I am trying to split a string of user input and store the parts in separate arrays. I am able to store the parts in one array, or in separate variables, but not in separate arrays. For example;



How can I make the variables into arrays?
I also need to be able to print the parts in a different order, for example if the user inputs

"Smallville : Springfield : 2 : 3"

the output would be

"Smallville [2] | Springfield [3]"

but would this be possible to do with an arrays? (Since there needs to be an undefined number of inputs before the user types "stop".)

I would really appreciate any kind of help with this, since I have been looking on Google for 3 days now and still can't work it out.

Thanks!



 
Carey Brown
Saloon Keeper
Posts: 3329
46
Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You already have a "splitInput" array, can't you work with that directly?
 
Carey Brown
Saloon Keeper
Posts: 3329
46
Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

 
Carey Brown
Saloon Keeper
Posts: 3329
46
Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you are trying to achieve arrays of arrays or multiple arrays then I suggest considering an object-oriented approach. Make a class GameScores with fields for homeTeam, homeScore, awayTeam, and awayScore. Create a constructor that can take those as parameters and initialize the various fields.

If you don't know how many lines you're going to read then arrays are very cumbersome and a List (e.g. List<GameScores>) would be way easier to deal with.

 
Campbell Ritchie
Marshal
Posts: 56584
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

I added code tags to your post. Always use the tags. Doesn't it look better
Your regular expression to split the input will match one colon followed by one space. You might consider changing it to \\s*:\\s+ which means any number of whitespace characters followed by one colon followed by any number greater than 0 of whitespace characters. Also look in the Scanner documentation for a suggestion of a different way to read things by changing the delimiter. Note that : is not a metacharacter for regular expressions (list available here in the Java™ Tutorials).
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!