Java: 2-dimensional char Array [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
i've been trying to programm a game called Sokoban the last few days. The levels of the game are simple .txt files you can swap. I've already read the .txt file by using BufferedReader but have problems with saving it to an 2-dimensional char array because the number of rows and columns are different each level. Someone told me to make use of charAt but how do i do that.
Sokobanlevel format (http://www.sokoban-online.de/help/sokoban/level-format.html)
Hope you can help me. Thanks.
String file = "...";
BufferedReader br = Files.newBufferedReader();
String line = null;
int rows = file.length;
int cols = file[0].length;
char[][] room = new char [rows][cols];
while ((line = br.readLine()) != null) {
System.out.println(room[rows][cols]);
}

Without knowlege about the number of lines in the file you need to read everything from the file first to determine the number of lines. This would be easiest, if you use a List<char[]> to store char arrays for each line.
You could easily write something with the same functionality as a one-liner in java 8 though:
File fl = new File(file);
char[][] array = Files.lines(fl.toPath()).map(String::toCharArray).toArray(char[][]::new);

You can initialize 2D arrays so that each row has a different number of columns:
char[][] c = new char[7][];
c[0] = new char[5];
c[1] = new char[3];
//etc

Related

How to store words from a text file into a String array in Java? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 months ago.
Improve this question
I need help in constructing a String array in Java which would store values from a text file (.txt). The file has 82094 lines where each line contains 1 word. So, in total there are 82094 words that I want to add to my array.
Here is the file path :
"F:/Word Game/Words List [UK ENGLISH].txt"
I have declared this array :
String words[]=new String[82094];
I'm not sure what to do next.
First of all, you need to read your file line by line, then put each line in an array. I strongly recommend you to use one of java.util.List<E>'s instances. I prefer java.util.ArrayList<E>
In short, ArrayList is more flexible than a plain native array because it's dynamic. It can grow itself when needed, which is not possible with the native array. ArrayList also allows you to remove elements that are not possible with native arrays. You can read more about it here.
List<String> words = new ArrayList<String>();
try (BufferedReader br = new BufferedReader(new FileReader("YOUR_FILE_PATH"))) {
String line;
while ((line = br.readLine()) != null) {
words.add(line);
}
}
Also since java 8, you can use java.util.Stream<T> to read a file:
List<String> words = new ArrayList<String>();
try (Stream<String> lines = Files.lines(Paths.get("YOUR_FILE_PATH"), Charset.defaultCharset())) {
lines.forEachOrdered(line -> words.add(line));
}

How to read a text file by skipping first and last line in a file [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I wanted to read a file line by line and store it to a variable. But, I want to skip the first and last line and store it to variable. How to do that?
Kindly help with a Java code to achieve this.
In Java 7 or Java 8 :
List<String> lines = Files.readAllLines(Paths.get("file.txt"));
if(!lines.isEmpty()) {
lines.remove(0);
}
if(!lines.isEmpty()) {
lines.remove(lines.size() - 1);
}
Remove the if conditions if you are certain the files contain at least 2 lines.
I recommend you to use an ArrayList to read the full file:
Scanner s = new Scanner(new File(//Here the path of your file));
ArrayList<String> list = new ArrayList<String>();
while (s.hasNext())
{
list.add(s.nextLine());
}
Now that you have stored all the lines of your file (as an ArrayList of String) you can operate with the data.
To operate with the data you just have to iterate through them by a loop:
for(int i = 1; i < list.size() - 1; i++)
{
String line = list.get(i);
System.out.println(line);
}
Look that I start on the position 1 and ends on the position list.size() - 1 to avoid the first and the last line of the file.
If you want to store your first line and your last line you can do:
String firstLine, lastLine;
firstLine = list.get(0);
lastLine = list.get(list.size());
I expect it will be helpful for you!

best solution for java txt project [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
Like topic says I'm looking for the best way to:
I got .txt file. In this file there are for example:
Matthew Sawicki 25\n
Wladimir Putingo 28\n
Barracko Obamaso 27
Whats the best way to write a program that opens this file, checks out the biggest number and then prints out that?
I was thinking about: open file -> check each line with hasNextLine method saving the biggest number (addin i for measuring the lines - 1, 2, 3) and then close file and open again and then somehow prints out that line
Ok there goes edit then.
By the way I have to write name of file in console to open it. And I have to use Scanner.
My code:
Scanner scanner= new Scanner (System.in);
File file = new File (scanner.nextLine);
scanner = new Scanner (file);
int temp=O;
int i=0;
while (scanner.hasNextLine) {
String word1=scanner.next;
String word2=scanner.next;
String word3=scanner.next;
If(word3>temp)
temp3=word;
i++; // now i get the i id of the line with the biggest number
And now I'm thinking bout reopen file and loop again to print out that line with the biggest number(By for instance if(newWord3==temp))
is it a good idea? And how to reopen the file? can anyone continue the code?
Assuming that this file will always be in the same format here's a snippet that does what you want with no checking to make sure that anything is in the wrong place/format.
//Create a new scanner pointed at the file in question
Scanner scanner= new Scanner(new File ("C:\\Path\\To\\something.txt"));
//Create a placeholder for the currently known biggest integer
int biggest = 0;
while (scanner.hasNextLine()) {
String s = scanner.nextLine();
//This line assumes that the third word separated by spaces is an
// integer and copies it to the `cndt` variable
int cndt = Integer.parseInt(s.split(" ")[2]);
//If cndt is bigger than the biggest recorded integer so far then
// copy that as the new biggest integer
biggest = cndt > biggest ? cndt : biggest;
}
//Voila
System.out.println("Biggest: " + biggest);
You'll want to verify that the number in question is there, and that you can handle the case that a line in your text file is malformed
There are several ways to do what you want. The way you described can work, but as you noted it requires to scan the file twice (in the worst case, which is when the row you have to print is the last one).
A better way which avoid to reopen the file again is to modify your algorithm to save not only the biggest number and the corresponding row number, but saving the whole line if the number is bigger than the one previously saved. Then, when you're done scanning the file you can just print the string you saved, which is the one containing the biggest number.
Note that your code will not work: the if is comparing a String with an int, and also there's no temp3 variable (that's probably just a typo).
To follow my suggestion you should have something like this:
int rowNumber = Integer.parseInt(word3);
if(rowNumber > temp) {
temp = rowNumber;
tempRow = word1 + " " + word2 + " " + word3;
}
then you can just print out tempRow (which you should define outside the while loop).
It's all fine now. I've made a simple mistake in my file (an empty enter at the end) so i coudnt figure out how to do it.
Thanks for ur effort and gl!.

linear search for a given string in java ? Are there any better solutions? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Sorry if my question is silly but I need some help.
Well, the problem is that I am trying to learn java and was trying to make a little program
that will search through the text file for a matching string that has been inserted in the
parameter. I wanted to know which part of the program should I fix to make the method work properly or at least want to know if there is a better solution.
public String linaerSearch(String filename,String strToArrays){
String[]arrays;
File f = new File("C:\\Users\\toyman\\Documents\\NetBeansProjects\\ToyMaker\\"+filename);
String[]items = (strToArrays.split("\\s*,\\s*"));//converting the string into arrays by comma
//convert the int into string
StringBuilder build = new StringBuilder();
if(f.exists()){ //checks if the file actually exists
try(FileInputStream fis = new FileInputStream(f)){
int con; int incrementor =0;
while((con=fis.read())!=-1){
incrementor++;
char str = (char)con;
String str2 = Character.toString(str);
if(items[ ????? ].equals(str2)){
// I want to check if the string that has been passed in the parameter
// exists in the file. But I got confused at the items[ ???? ].
System.out.println("found you");
}
//System.out.println();
//convert to char and display it
System.out.print(str2);
}
}catch(Exception e){
e.printStackTrace();
}
}else{
System.out.println("The file doesn't exist. Create a new file or use a existing file");
}
return "";
}
If you want to search for some string in a text, and do it properly, it has nothing to do with Java. What you're looking for is a string searching algorithm.
Try looking in Wikipedia: http://en.wikipedia.org/wiki/String_searching_algorithm
I'd suggest going for either:
Rabin–Karp algorithm: http://en.wikipedia.org/wiki/Rabin%E2%80%93Karp_string_search_algorithm
Knuth–Morris–Pratt algorithm: http://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm
They are both really good and efficient algorithms, and both are fairly easy to implement.

Reading a text file, character by character in java [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I am currently trying to work with a custom text file to read quests for a small game, however i am having trouble getting the code to read each character, I've done my research and somehow come up with nothing. I am unsure of how to read a .txt file character by character, so if anyone can help or point me in the right direction it would be strongly appreciated.
Path path = Paths.get("filename");
try (Scanner scanner = new Scanner(path, ENCODING.name())){
while (scanner.hasNextLine()){
String s = scanner.nextLine();
for(char c : s.toCharArray()) {
// your code
}
} catch(IOException e) {/* Reading files can sometimes result in IOException */}
If you want to read each character from file you could do something like this:
BufferedReader r=new BufferedReader(new FileReader("file.txt"));
int ch;
while((ch=r.read())!=-1){
// ch is each character in your file.
}
Good luck
File file = new File("text.txt");
Scanner in = new Scanner(file);
// option 1
while(in.hasNext())
{
String temp = in.next();
char[] temparr = temp.toCharArray();
for(Character j: temparr)
{
//do someting....
}
}
// or option 2
in.useDelimiter("");
while(in.hasNext())
{
temp = in.next();
//do something
}
Option 1 gives you the ability to manipulate the string char by char if the condition is true.
Option just reads one char at a time and lets you preform an action but not manipulate the string found in the text file.
public void method() throws FileNotFoundException
if you dont want to use a try catch

Categories