I am creating a function to print a mase, which is stored in a 2 Dimensional ArrayList<ArrayList<String>>. However, the function instead prints out a large portion of blank space. I am attempting to first iterate through each ArrayList<String> and then iterate through each String element inside the nested ArrayList<String>s. I am creating the ArrayList<ArrayList<String>> from reading a file.
Here is the file:
XXXXXXXXSOOOOXXXXXX
XXXXXXXXXXXXOXXXXXX
XXXXXXXXXXXXOXXXXXX
XXXXXXXXXXXXOXXXXXX
XXXXXXXOOOOOXXXXXX
XXXXXXXOXXXXXXXXXXX
XXXXXXXEXXXXXXXXXXX
Here is where I create it:
String fileName = "maze.txt";
String line = null;
ArrayList<ArrayList<String>> lines = new ArrayList<ArrayList<String>>();
// Setup FileReader, BufferedReader, and LineReader
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
// Get all the lines inside the maze file
while ((line = bufferedReader.readLine()) != null)
{
ArrayList<String> lineList = new ArrayList<String>();
for (int i = 0; i < line.length(); i++)
{
lineList.add(line.substring(i, i));
}
lines.add(lineList);
}
Here is my function:
public static void printMase(ArrayList<ArrayList<String>> lines)
{
for (ArrayList<String> row: lines)
{
for (String elem: row)
{
System.out.println(elem);
}
}
}
There are just some minor mistakes in your code. Make the following changes.
// This is adding a blank space
lineList.add(line.substring(i, i));
To
// This will add a single character
lineList.add(line.substring(i, i+1));
and modify printMase(ArrayList<ArrayList<String>> lines)
public static void printMase(ArrayList<ArrayList<String>> lines)
{
for (ArrayList<String> row: lines)
{
for (String elem: row)
{
// Using print so each character is on the same line
System.out.print(elem);
}
// Now use println to end the line
System.out.println();
}
}
Full code looks like:
public static void main(String[] args) throws Exception {
String fileName = "maze.txt";
String line = null;
ArrayList<ArrayList<String>> lines = new ArrayList<>();
// Setup FileReader, BufferedReader, and LineReader
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
// Get all the lines inside the maze file
while ((line = bufferedReader.readLine()) != null) {
ArrayList<String> lineList = new ArrayList<>();
for (int i = 0; i < line.length(); i++) {
// Adds a single character
lineList.add(line.substring(i, i+1));
}
lines.add(lineList);
}
printMase(lines);
}
public static void printMase(ArrayList<ArrayList<String>> lines)
{
for (ArrayList<String> row: lines)
{
for (String elem: row)
{
// Using print so each character is on the same line
System.out.print(elem);
}
// Now use println to end the line
System.out.println();
}
}
Results:
XXXXXXXXSOOOOXXXXXX
XXXXXXXXXXXXOXXXXXX
XXXXXXXXXXXXOXXXXXX
XXXXXXXXXXXXOXXXXXX
XXXXXXXOOOOOXXXXXXX
XXXXXXXOXXXXXXXXXXX
XXXXXXXEXXXXXXXXXXX
Woops, I realized that I was adding blank space during initialization. I updated my code such that it was adding the actual characters:
String fileName = "maze.txt";
String line = null;
ArrayList<ArrayList<String>> lines = new ArrayList<ArrayList<String>>();
// Setup FileReader, BufferedReader, and LineReader
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while ((line = bufferedReader.readLine()) != null)
{
ArrayList<String> lineList = new ArrayList<String>();
for (int i = 0; i < line.length(); i++)
{
lineList.add(Character.toString(line.charAt(i)));
}
lines.add(lineList);
}
Related
So i have an array int[] numbers = {1,2};
But i want the 1,2 to be removed and replaced with numbers from an txt file.
I can see the numbers from the files in the console with this method:
public String[] readLines(String filename) throws IOException {
FileReader fileReader = new FileReader(filename);
BufferedReader bufferedReader = new BufferedReader(fileReader);
List<String> lines = new ArrayList<String>();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
lines.add(line);
}
bufferedReader.close();
return lines.toArray(new String[lines.size()]);
}
public static void testFileArrayProvider() throws IOException {
algo1 fap = new algo1();
String[] lines = fap
.readLines("D:/Users/XXX/workspace/abc/src/abc1/Filename123");
for (String line : lines) {
System.out.println(line);
}
}
NOw i need to save them in the array. BUt how? xd
Thx guys
This should work:
// In your case this is already populated
String[] lines = new String[] {"123", "4567"};
// Easier to work with lists first
List<Integer> results = new ArrayList<>();
for (String line : lines) {
results.add(Integer.parseInt(line));
}
// If you really want it to be int[] for some reason
int[] finalResults = new int[results.size()];
for (int i = 0; i < results.size(); i++) {
finalResults[i] = results.get(i);
}
// This is only to prove it worked
System.out.println(Arrays.toString(finalResults));
In Java-8, you can shorten it to
int[] finalResults = Arrays.stream(lines).mapToInt(Integer::parseInt).toArray();
I am trying to save the contents of a word file line by line into a LinkedList.
What am I doing wrong? The console is showing that it is definatley reading the file but not saving its contents?
public class SpellCheck {
LinkedList<String> lines = new LinkedList();
boolean suggestWord ;
public static void main(String[] args) throws java.io.IOException{
System.out.println("Welcome to the spellchecker");
LinkedList<String> list = new LinkedList<String>();
try {
File f = new File("input/dictionary.txt");
FileReader r = new FileReader(f);
BufferedReader reader = new BufferedReader(r);
String line = null;
String word = new String();
while((line = reader.readLine()) != null)
{
list.add(word);
word = new String();
}
reader.close();
}catch(IOException e) {
e.printStackTrace();
}
for(int i = 0; i<list.size();i++){
System.out.println(list.get(i));
}
}
}
You are adding word which is an empty string instead of adding line which you read from file:
String word = new String();
while((line = reader.readLine()) != null)
{
list.add(word);
^^^^^
word = new String();
}
It should be:
while((line = reader.readLine()) != null) {
list.add(line);
}
import java.util.*;
import java.io.*;
public class readFiles2 {
public static void main(String[] args) throws IOException{
// TODO Auto-generated method stub
BufferedReader reader = new BufferedReader(new FileReader("someFile.txt"));
try{
StringBuilder text = new StringBuilder();
String readStringLine = reader.readLine();
String[] lines= {};
for(int i = 0; readStringLine != null; i++){
readStringLine = reader.readLine();
//Trying to save seperate lines of text in an array.
lines[i] = readStringLine.toString();
}
}
finally{
reader.close();
}
}
So what I'm trying to do is save separate lines of strings from a .txt file to a String[] array. I'm kind of at a loss right now and don't really know what else I can do.
Since you don't know how many strings there are for your array, you might want to put the strings in a list and convert to an array at the end:
String readStringLine;
List<String> lines = new ArrayList<String>();
while((readStringLine = reader.readLine()) != null) {
lines.add(readStringLine);
}
String[] linesArray = lines.toArray(new String[lines.size()]);
Edit: Simpified to use a while loop to gather the line from the reader.
ArrayList<String> line = new ArrayList<>();
FileReader file = new FileReader(file.txt);
BufferedReader reader = new BufferedReader(file);
while (reader.ready()) {
line.add(reader.readLine());
reader.close();
file.close();
}
To acess, use line.get(i); where i>=0 and i<=array.size
Using autocloseable interface and Java 8 streams:
String [] stringsArray = null;
try(BufferedReader br = new BufferedReader(new FileReader("someFile.txt"))) {
List<String> strings = new ArrayList<>();
br.lines().forEach(c -> strings.add(c));
stringsArray = strings.toArray(new String[strings.size()]);
}
You need Java 8 to run this code
Making a hangman style of game
I have the random word now. How do I replace the letters of the word with an asterix * so that when the program starts the word is shown as *.
I assume that when someone inputs a letter for the hangman game you get the index of that character in the word and then replace the corresponding *.
public class JavaApplication10 {
public static String[] wordArray = new String[1];
public static String file_dir = "Animals.txt";
public static String selectedWord = "";
public static char[] wordCharacter = new char[1];
Scanner sc = new Scanner(System.in);
public static void main(String[] args) throws IOException {
wordArray = get_word(file_dir);
selectedWord = select_word(wordArray);
System.out.println(selectedWord);
}
public static String[] get_word(String file_dir) throws IOException {
FileReader fileReader = new FileReader(file_dir);
BufferedReader bufferedReader = new BufferedReader(fileReader);
List<String> lines = new ArrayList<String>();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
lines.add(line);
}
bufferedReader.close();
return lines.toArray(new String[lines.size()]);
}
public static String select_word(String[] wordArray) {
Random rand = new Random();
int lines = Math.abs(rand.nextInt(wordArray.length)- 1);
return wordArray[lines];
}
}
If you know how many lines are there you could use Random method in java with a specific range to pick out a line at random.
Then you could read the file line-by-line till you reach that random line and print it.
// Open the file
FileInputStream fstream = new FileInputStream("testfile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
int counter=0;
//While-loop -> Read File Line By Line till the end of file
//And will also terminate when the required line is printed
while ((strLine = br.readLine()) != null && counter!=randomValue){
counter++;
//You need to set randomValue using the Random method as suggested
if(counter==randomValue)
// Print the content on the console
System.out.println (strLine+"\n");
}
//Close the input stream
br.close();
Assuming Java 8:
// Loading ...
Random R = new Random(System.currentTimeMillis());
List<String> animals = Files.readAllLines(Paths.get(path));
// ...
// When using
String randomAnimal = animals.get(R.nextInt(animals.size()));
Answer of your first question :
First you have to get the total number of lines
Then you have to generate a random number between 1 and that total number.
Finally, get the required word
try {
InputStream is = new BufferedInputStream(new FileInputStream("D:\\test.txt"));
byte[] c = new byte[1024];
int count = 0;
int readChars = 0;
boolean empty = true;
while ((readChars = is.read(c)) != -1) {
empty = false;
for (int i = 0; i < readChars; ++i) {
if (c[i] == '\n') {
++count;
}
}
}
int noOfLines = count+1;
System.out.println(noOfLines);
Random random = new Random();
int randomInt = random.nextInt(noOfLines);
FileReader fr = new FileReader("D:\\test.txt");
BufferedReader bufferedReader =
new BufferedReader(fr);
String line = null;
int counter =1;
while((line = bufferedReader.readLine()) != null) {
if(counter == randomInt)
{
System.out.println(line); // This the word you want
}
counter++;
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
finally {
//is.close();
}
I saved some of my ArrayList's to a file and it has following format:
[hotel1, hotel2, hotel3] // ArrayList 1 contents
[hotel5, hotel6] // ArrayList 2 contents
When I am reading, I want to assign for example an ArrayList myList, and I want to add hotel1, hotel2 and hotel3 to myList. Any way I can do that directly? Currently I have a string value that reads next line, it saves brackets. Was looking for another way, so that I can assign each line to an ArrayList < String > object.
public class MyClass1 {
ArrayList<String> myList = new ArrayList<String>();
... // some other code
private void loadUp() throws IOException{
JFileChooser chooser = new JFileChooser();
chooser.setDialogTitle("Choose a file to open...");
checker = chooser.showOpenDialog(null);
// if open is clicked
if (checker == JFileChooser.APPROVE_OPTION) {
File inFile = chooser.getSelectedFile();
Scanner in = new Scanner(inFile);
while (in.hasNextLine()) {
// Here want to assign next line to myList
}
in.close();
}
}
Use this:
Scanner file = new Scanner(myFile);
ArrayList<Scanner> lines = new ArrayList<>();
while(file.hasNextLine())
lines.add(new Scanner(file.nextLine()));
ArrayList<ArrayList<String>> lists = new ArrayList<>(lines.size());
for(Scanner s : lines)
s.useDelimeter("[, ]" + System.lineSeparator());
for(int i = 0; i < lines.size(); ++i)
{
while(lines.get(i).hasNext())
{
lists.add(new ArrayList<String>());
lists.get(i).add(lines.get(i).next());
}
}
Then you'll end up with a list of lists of strings that contain the values.
Try below code to read each line
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
// process the line.
}
br.close();