Had a quick question based on an assignment I'm working on.
I have a list of numbers like this in a text file:
5, 8, 14
7, 4, 2
And I need them inserted into an array as such
joe[5][8] = 14;
joe[7][4] = 2;
Having trouble getting this done, thanks to anyone who can give me a hand.
-Edit-
This is the code I have now
File f = new File("solution.txt");
Scanner sc = new Scanner(f);
while(sc.hasNextLine())
{
if(sc.hasNextInt())
x = sc.nextInt();
if(sc.hasNextInt())
y = sc.nextInt();
if(sc.hasNextInt())
joe[x][y] = sc.nextInt();
}
Try instantiating a 2 dimensional array then reading each line, and then each of the three numbers from each line. Use the first 2 numbers as the array indices and the last as the value.
Some example code
You have to specify the
,
as a separator.Try this:
sc.useDelimiter("[,]+");
Then your code is:
This may not be the most efficient way but it allows for unknown array distentions.
Take an entire line an split the line into a String array using the method
split
as exemplified below. Then take each element of the String array and convert it to anint
using the methodInteger.parseInt( )
. Your code should look something like: