Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

User input into array

 
Ron Ingram
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

Im working on the magic squares assignment and the tester asks the user to input values on a single line to be used for the magic square class. My problem is how do I take values given on one line and seperate them into an array or 2D array?

This is an example user input:

Enter a sequence of integers, followed by Q:
16 3 2 13 5 10 11 8 9 6 7 12 4 15 14 1
Q

I'm trying to take the values and insert them into a StringBuilder then back toString() which does a good job seperating them by the space, but how do I put them into an array?

Here are my classes so far


Here is the tester class:
 
Wouter Oet
Saloon Keeper
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can use String.split() to split the string into an array of strings. Then you'll need to parse the String to an int.
 
Winston Gutkowski
Bartender
Pie
Posts: 10103
56
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ron Ingram wrote:Im working on the magic squares assignment and the tester asks the user to input values on a single line to be used for the magic square class. My problem is how do I take values given on one line and seperate them into an array or 2D array?

Well, as Wouter said, String.split() will create an array of the number strings for you. The problem is that it will be a one-dimensional array of String[16], and I presume that you want to convert that into an int[4][4].

My suggestion: have a look at the '/' and '%' operators, and think about what they do.

It might also be worth going through all the index values for your String[] and printing out the results.

Winston
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic