| Author |
User input into array
|
Ron Ingram
Ranch Hand
Joined: Mar 11, 2011
Posts: 60
|
|
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
Joined: Oct 25, 2008
Posts: 2700
|
|
|
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.
|
"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
|
 |
Winston Gutkowski
Bartender
Joined: Mar 17, 2011
Posts: 4761
|
|
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
|
Isn't it funny how there's always time and money enough to do it WRONG?
|
 |
 |
|
|
subject: User input into array
|
|
|