This week's book giveaway is in the Java 8 forum.
We're giving away four copies of Java 8 in Action and have Raoul-Gabriel Urma, Mario Fusco, and Alan Mycroft on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes User input into array Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "User input into array" Watch "User input into array" New topic
Author

User input into array

Ron Ingram
Ranch Hand

Joined: Mar 11, 2011
Posts: 63
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: 7081
    
  16

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?
Artlicles by Winston can be found here
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: User input into array
 
Similar Threads
Teach me to program!!
Largest/Greatest of n numbers
problems with math methods
Problem.
simple array loop