Reputation: 13
I am trying to store the content of my text file into an arrays and display them in the console. I also want to find the empty space in the file and insert a game board there which I designed earlier.
Here is my text file content:
rfhrf
1
4
sdtgv
1
1
rfhrf
1
3
sdtgv
2
1
rfhrf
4
4
sdtgv
3
1
and here is what I have so far:
File text = new File("actions.txt");
try {
Scanner scanner = new Scanner(text);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
Thread.sleep(5000);
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
any help would be great.
Upvotes: 1
Views: 1584
Reputation: 171
I think you don't need to use Array. Just try the following! Hope it works!
File text = new File("actions.txt");
try {
Scanner scanner = new Scanner(text);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line.isEmpty()) {
System.out.println("This is Space!");
} else {
System.out.println(line);
}
Thread.sleep(5000);
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
Upvotes: 1
Reputation: 7226
What you could do is define a format by convention, alterating your file, to make it look like this:
rfhrf;1;4
sdtgv;1;1
...
and then for every read line, you can see the value and the position. Example:
File text = new File("actions.txt");
try {
Scanner scanner = new Scanner(text);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String params = line.split(";");
String value = params[0];
int row = Integer.parseInt(params[1]);
int col = Integer.parseInt(params[2]);
myArray[row][col] = value;
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
That should help you, if I actually understood what you meant.
Upvotes: 1
Reputation: 164
Do your own class that provides all your needs(like space counts,words) let's say MyClassContainer and then put all your MyClassContainer in a hashtable.It is quick and easy
Upvotes: 0