String tokenizer and parsing plain text JAVA - java

I am making a simple text based card game for fun/practice with parsing files. I have a plain text file with all the specs for the card. My cards are split with "##########". They are multilined. For now I simply want to be able to pull up the entirety of any ONE card whenever I want. For example, Player picks character 1, so I pull up Card 1 Only? How ?
EXAMPLE:
##########
CARD 1
Character Name:
Something Else:
##########
CARD 2
Character Name:
Something Else:
##########
Character Name:
Something Else:
##########
HOW CAN I ACTUALLY SPLIT THE CARDS SO THAT I CAN JUST ASK THE USER WHICH CARD.
I don't want to have to read the lines and print the way I did. It is rather cumbersome and convoluted.
My NEW ATTEMPT:
ArrayList listForCard1 = new ArrayList();
Integer selected_card = 1;
try {
String line;
FileReader fR = new FileReader("MyText.txt");
BufferedReader br = new BufferedReader(fR);
int x = 0;
Integer card = 1;
while ((line = br.readLine()) != null) {
ALines[x] = line;
x++;
if (line.contains("##########")) {
if ( card == selected_card) {
listForCard1.add(br.readLine());
// System.out.println(br.readLine());
break;
} else {
card++;
}
}
}
System.out.println("Done");
System.out.println(ALines[0]);
System.out.println(ALines[1]);
System.out.println(ALines[2]);
System.out.println(ALines[3]);
System.out.println(ALines[4]);
System.out.println(ALines[5]);
System.out.println(ALines[6]);
} catch (IOException e) {
e.printStackTrace();
}
}

try this
ArrayList<String> listForCard1 = new ArrayList<String>();
Integer selected_card = 1;
BufferedReader br = null;
try {
String line;
br = new BufferedReader(new FileReader("MyText.txt"));
Integer card = 1;
while ((line = br.readLine()) != null) {
if (line.contains("##########")) {
if ( card == selected_card) {
listForCard1.add(br.readLine());
listForCard1.add(br.readLine());
listForCard1.add(br.readLine());
break;
} else {
card++;
}
}
}
System.out.println("Done");
for (String s : listForCard1) {
System.out.println(s);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
select the card by setting selected_card.. we count how many #####'s we see when we have seen enough we read out that card and stop reading the file.. then print it from the arraylist

Related

How would I print out the first word of each line?

I have a text file that reads like this:
1. Bananas that are not green
2. Pudding that is not vanilla
3. Soda that is not Pepsi
4. Bread that is not stale
I just want it to print out the first word of each line
NOT INCLUDING NUMBERS!
It should print out as:
Bananas
Pudding
Soda
Bread
Here is my code:
public static void main(String[] args) {
BufferedReader reader = null;
ArrayList <String> myFileLines = new ArrayList <String>();
try {
String sCurrentLine;
reader = new BufferedReader(new
FileReader("/Users/FakeUsername/Desktop/GroceryList.txt"));
while ((sCurrentLine = reader.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
System.out.print(e.getMessage());
} finally {
try {
if (reader != null)reader.close();
} catch (IOException ex) {
System.out.println(ex.getMessage());
ex.printStackTrace();
}
}
}
Use the split function of String. It returns the array of the String as per the character which we want to split with the string. In your case, it is like as follow.
String sCurrentLine = new String();
reader = new BufferedReader(new
FileReader("/Users/FakeUsername/Desktop/GroceryList.txt"));
while ((sCurrentLine = reader.readLine() != null) {
String words[] = sCurrentLine.split(" ");
System.out.println(words[0]+" "+words[1]);
}
Java 8+ you can use the BufferedReader's lines() method to do this very easily:
String filename = "Your filename";
reader = new BufferedReader(new FileReader(fileName));
reader.lines()
.map(line -> line.split("\\s+")[1])
.forEach(System.out::println);
Output:
Bananas
Pudding
Soda
Bread
This will create a Stream of all the lines in the BufferedReader, split each line on whitespace, and then take the second token and print it
Please try the code below -:
outerWhileLoop:
while ((sCurrentLine = reader.readLine()) != null) {
//System.out.println(sCurrentLine);
StringTokenizer st = new StringTokenizer(sCurrentLine," .");
int cnt = 0;
while (st.hasMoreTokens()){
String temp = st.nextToken();
cnt++;
if (cnt == 2){
System.out.println(temp);
continue outerWhileLoop;
}
}
}

Empty line in arraylist Java

protected synchronized static void getRandomProxy(String srcFile) throws FileNotFoundException {
List<String> words = new ArrayList<>();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(srcFile));
String line;
while ((line = reader.readLine()) != null) {
words.add(line);
System.out.println(line);
}
int k = 0;
for (int i = 0; i < words.size(); i++) {
k++;
String[] splitted = words.get(i).split(":");
String ip = splitted[0];
String port = splitted[splitted.length - 1];
// System.out.println(k + " " + ip + " * " + port);
}
} catch (IOException iOException) {
} finally {
try {
reader.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
I want to get output printed without empty lines .
These are kind of results am getting Like :
result 1.
result 2.
result 3.
i want output like :
result 1.
result 2.
result 3.
without blank lines.
Don't add the String to the list if it's empty :
if(!line.trim().isEmpty()) {
words.add(line);
System.out.println(line);
}
If you still want to add the blank lines to the list but don't display them, just move the condition :
words.add(line);
if(!line.trim().isEmpty())
System.out.println(line);
Doc
Use System.out.print. Note that the file contains a newline char at the end of each line.
If srcFile is created with Notepad, try removing first the carriage return char System.out.print(line.replaceAll("\\r",""))
ArrayList<String> words = new ArrayList<>();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(srcFile));
String line;
while ((line = reader.readLine()) != null) {
line = line.trim(); // remove leading and trailing whitespace
if (!line.isEmpty() && !line.equals("")) {
words.add(line);
System.out.println(line);
}
}

reading crossword puzzle txt file

I am new at JAVA and i got no idea how to start this. I was looking for a good start. I need to read a txt file that has a certain format and put it into a view. i first need to read the dimensions of the grid, then the words in the order of the puzzle, then the amount of words needed to be found and last the actual word. If anyone can get me into the right direction with an example, that would really help.
this is the format of the txt file
5 5
abcd
dfad
adfe
lkjl
ekkf
5
realword
realword
realword
realword
realword
EDIT: so this is what i tried after testing to read out the file which works (thanks!). but i get stuk here, i still need to change from char[][] to box[][], since i will be needing it to fill the letterGrid.
import java.io.*;
import java.util.List;
public class Puzzle {
//Box[][] letterGrid;
char[][] letterGrid;
List<Word> wordList;
List<Box> wordInWording;
public Puzzle() {
try {
BufferedReader br = new BufferedReader(new FileReader("..\\word.txt"));
String[] dimensions = br.readLine().split(" ");
letterGrid = new char[Integer.parseInt(dimensions[0])][Integer.parseInt(dimensions[1])];
for (int i = 0; i < letterGrid[0].length; i++) {
String val = br.readLine();
letterGrid[i]= val.toCharArray();
}
//while something something
int r = br.read();
int c = br.read();
letterGrid = new char[r][c];
for (int i = 0; i<r; i++){
String getChar = new String(br.readLine());
for(int j=0; j<c; j++){
letterGrid[i][j] = getChar.charAt(j);
}
}
// String sCurrentLine;
// while ((sCurrentLine = br.readLine()) != null) {
// System.out.println(sCurrentLine);
// }
} catch (IOException e) {
e.printStackTrace();
}
}
}
Here is a good Start:
I will just give you hint on how to read lines from a text file. YOu have to build the logic on your own after reading from it.
public static void main(String[] args) {
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("C:\\testing.txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
You are not supposed to post such questions in SO without even giving it a try. Try to code, if you get stuck post it then and ask for help. Community does not encourage such questions.

How do I skip lines when I'm reading from a text file?

I'm reading from a text file which looks like this:
1
The Adventures of Tom Sawyer
2
Huckleberry Finn
4
The Sword in the Stone
6
Stuart Little
I have to make it so that the user can enter the reference number and the program will perform binary and linear search and output the title. My teacher said to use two ArrayLists, one for the numbers and one for the titles, and output from them. I just can't figure out how to skip lines so I can add to the corresponding arraylist.
int number = Integer.parseInt(txtInputNumber.getText());
ArrayList <String> books = new ArrayList <>();
ArrayList <Integer> numbers = new ArrayList <> ();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("bookList.txt"));
String word;
while ((word = br.readLine()) != null ){
books.add(word);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
Thanks in advance, I appreciate any help!
You can check if you are in even or odd lines by doing a modulo 2 operation on the line number:
try (BufferedReader br = new BufferedReader(new FileReader("bookList.txt"))) {
String word;
int lineCount = 0;
while ((word = br.readLine()) != null ){
if (++lineCount % 2 == 0) {
numbers.add(Integer.parseInt(word));
} else {
books.add(word);
}
}
} catch (IOException e) {
e.printStackTrace();
}
int number = Integer.parseInt(txtInputNumber.getText());
ArrayList <String> books = new ArrayList <>();
ArrayList <Integer> numbers = new ArrayList <> ();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("bookList.txt"));
String word;
while ((word = br.readLine()) != null ){
numbers.add(Integer.valueOf(word));
word = br.readLine()
books.add(word);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
You could make check to see if it is actually a integer, that you read from the file. As far as I remember, there is no built in method to do this, but you can define your own as:
boolean tryParseInt(String value) {
try {
Integer.parseInt(value);
return true;
} catch (NumberFormatException e) {
return false;
}
}
Then just make a check to see if the line you have read in is a integer or not.
int number = Integer.parseInt(txtInputNumber.getText());
ArrayList <String> books = new ArrayList <>();
ArrayList <Integer> numbers = new ArrayList <> ();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("bookList.txt"));
String word;
while ((word = br.readLine()) != null ){
if (tryParseInt(word))
numbers.add(Integer.parseInt(word))
else
books.add(word);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
Hope this help!

converting lines of imported text file to arrays and printing arrays to make graph in Netbeans and Swing

I want to import any .txt files (note the .txt files will have a 3 sets of numbers in one column; separating each set with a space)
2
3
4
3
2
1
1
2
3
and convert the set of numbers into arrays. (array 1 , 2 and 3)
array1[] = {2,3,4}
array2[] = {3,2,1}
array3[] = {1,2,3}
then be able to graph the array in JFreeGraph Library
here's how i started...i'm using netbeans and java Swing
#Action
public void openMenuItem() {
int returnVal = jFileChooser1.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = jFileChooser1.getSelectedFile();
try {
FileReader fileReader = new FileReader(file);
jTextArea2.read(new FileReader(file.getAbsolutePath()), null);
} catch (IOException ex) {
System.out.println("problem accessing file" + file.getAbsolutePath());
}
} else {
System.out.println("File access cancelled by user.");
}
}
Read from a file line by line, perhaps using BufferedReader and readLine. Once you encounter an empty line - you have a new set of numbers. Here is an oversimplified example that maintains a list of lists, and reads only strings:
public static List<List<String>> parseFile(String fileName){
BufferedReader bufferedReader = null;
List<List<String>> lists = new ArrayList<List<String>>();
List<String> currentList = new ArrayList<String>();
lists.add(currentList);
try {
bufferedReader = new BufferedReader(new FileReader(fileName));
String line = null;
while ((line = bufferedReader.readLine()) != null) {
if (line.isEmpty()){
currentList = new ArrayList<String>();
lists.add(currentList);
} else {
currentList.add(line);
}
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (bufferedReader != null)
bufferedReader.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
return lists;
}
EDIT: using resulting lists with JTextArea
List<List<String>> lists = parseFile("test.txt");
for (List<String> strings : lists){
textArea.append(StringUtils.join(strings, ",") + "\n");
System.out.println(StringUtils.join(strings, ","));
}

Categories

Resources