Store a text lines in an array in java - java

I have some texts which contain some lines. There is a word in every line. I should copy the text and then paste it to the Eclipse Console Output window and finally store each line in an array.
I don't know how many lines does each text have. How could I do this?
I know if I want to store some strings to an array I should do like bellow, but I don't want to do by this method:
String[] Lines = {"line1", "line2", ....};

If you don't know how many lines you will have you could use a generic list.
List<String> lines = new ArrayList<String>();
This will resize dynamically as you add values to it.
You could also use arrays and do the resizing yourself, which is what the ArrayList does behind the scenes, it's just that it adds complexity to your code.

You can not change an array size after you initialize it. If you change your previous data will be lost. You can use ArrayList to add items dynamically. For example;
ArrayList<String> list = new ArrayList<>();
//read your file here and print it. After that;
list.add(line); // I assumed you get lines to a variable called line

If you are using JDk 7+ you could easily do this by
List<String> list = Files.readAllLines(new File("test.txt").toPath());
But if you still want to use array convert that list to array like
List<String> list = Files.readAllLines(new File("test.txt").toPath());
String[] str = list.toArray(new String[list.size()]);
Or if you dont have a file and copy pasting to console try this
List<String> lines = new ArrayList<String>();
Scanner s = new Scanner(System.in);
while(s.hasNextLine()){
String line = s.nextLine();
if(line.length() > 0) {
lines.add(s.nextLine());
} else {
break;
}
}
System.out.println(lines);

Related

Problems changing from Enhanced for loop to normal for loop

I am extracting data from a csv format to java. I have written some code for it.
Reader reader = Files.newBufferedReader(Paths.get(FilePath));
CSVReader csvReader = new CSVReaderBuilder(reader).build();
List<String[]> records = csvReader.readAll();
for(String[] record : records) {
System.out.println(record[0]); // Note : Each record has two strings in it separated by delimiter ";"
String[] parts = record[0].split(";"); //So I am splitting here
System.out.println(parts[0]); //First part
System.out.println(parts[1]); //Second part
}
My main aim is to store the parts after splitting each String from an array of Strings i.e., from "records". The console gives the output as how I expected. But I don't want to print on console but store it in two different ArrayLists.
Hence I tried to change the for loop to a normal for loop as follows:
ArrayList<List<String>> separatedTime = new ArrayList<List<String>>();
ArrayList<List<String>> separatedValues = new ArrayList<List<String>>();
String[] Array = new String[records.size()];
for(int i = 0; i < records.size(); i++) {
Array[i] = (records[i]); //Error : Type of expression must be an array type. But it is resolved to List<String[]>
String[] parts = Array[i].split(";");
separatedTime.add(parts[0]); //Error : The method add(List<String>) in the type ArrayList<List<String>> is not applicable for the arguments (String)
separatedValues.add(parts[1]);
}
But this doesnot work. I cannot figure out why is it not working
1) if it is changed from enhanced for loop to normal for loop. If I am wrong, how can I change to normal for loop?
2) After splitting with delimiter in normal for loop, why am I not able to store in Array List
I know I somewhere, somehow stepped into wrong. But unable to find out how can I rectify
Got it!! I solved using the following :
String[] Array = null;
for(int i=0; i<records.size();i++)
{
Array = (records.get(i));
String[] parts = Array[0].split(";");
separatedTime.add(parts[0]);
separatedValues.add(parts[1]);
}
Everything is solved.. Thank you all for your time

I have one text file and in that text file I stored words in 2 columns. I want to store first column in one array and second column in another array

I separate two columns by tab. I have done following code for that but with that code I got one column in one array as a whole. I want to access each element individually and I want to store two columns in two arrays using java.
In splitting[0], I have first array and in splitting[1] I stored second column elements. Now I want to access each element individually using Java.
for(int i=0;i<lines.size();i++){
String[] splitting = lines.get(i).split("\t");
}
You could use Scanner to specify delimiter as tab..and use dynamic array i.e. ArrayList for adding columns.
BufferedReader reader= new BufferedReader(new FileReader("D:/sagar.txt"));
Scanner sc= new Scanner(reader);
sc.useDelimiter("\\s+"); // regex for specifying one or more tabs
List<String> a=new ArrayList<String>();
List<String> b =new ArrayList<String>();
while((sc.hasNextLine())){
a.add(sc.next());
b.add(sc.next());
}
System.out.println("First Column");
for (String string : a) {
System.out.println(string);
}
System.out.println("Second Column");
for (String string : b) {
System.out.println(string);
sagar.txt
hi ssup
hello gm
Create two more arrays.
Put this after your split.
array1[i] = splitting[0];
array2[i] = splitting[1];`
You need to set the size of the two new arrays to lines.size(). I would use List instead of Array.

Adding Input to JTextArea to an ArrayList of ArrayLists

My objective is to add the text from a JTextArea into an ArrayList of ArrayLists, such that each line of text inputted is saved as an ArrayList, with the words of that particular line saved as elements within the ArrayList of that line. I have an idea of how to store each line of the inputted text as an element within an ArrayList, but not how to have an ArrayList of ArrayLists. Could anyone point me in the right direction here? I would like to create a 2D ArrayList and was thinking something like this:
ArrayList[][] poem = new ArrayList[][];
This is what I was thinking for making an ArrayList containing each line as an element, but I would like to have each of the lines as a seperate ArrayList containing their respective words as elements:
JTextArea txArea = new JTextArea();
String txt = txArea.getText();
String [] arrayOfLines = txt.split("\n");
ArrayList<String> linesAsAL = new ArrayList<String>();
for(String line: arrayOfLines){
linesAsAL.add(line);
}
In sum, I am trying to make a 2D ArrayList, where each word inputted into a JTextArea would be added into its own cell within that 2D ArrayList.
Your question doesn't have to be JTextArea-specific, so my answer won't (I'm assuming you know how to get a string from a JTextArea. Hint: http://docs.oracle.com/javase/7/docs/api/javax/swing/JTextArea.html).
Here's a method to transform a String into an ArrayList<ArrayList<String>>:
public static List<List<String>> linesToLinesAndWords(String lines) {
List<List<String>> wordlists = new ArrayList<>();
List<String> lineList = Arrays.asList(lines.split("\n"));
for (String line : lineList) {
wordlists.add(Arrays.asList(line.trim().split(" ")));
}
return wordlists;
}
After seeing your code, I also suggest you learn Java.
The following work's
String content = jta.getText(); //jta = Instance of JTextArea
List<List<String>> list = new ArrayList<ArrayList<String>>();
for (String line : content.split("\n"))
{
String words[] = line.split("\\s");
list.add(new ArrayList<String>(Arrays.asList(words)));
}

Read a file and convert it to an array (Java)

So I have a collection of phrases that are separated by newlines and I would like to populate an array with these phrases. This is what I have so far:
Scanner s;
s = new Scanner(new BufferedReader(new FileReader("Phrases.txt")));
for(i = 0; i < array.length;i++)
{
s.nextLine() = array[i];
}
Is there a fast and simple way to just populate an array with phrases separated by newlines?
The assignment should be reverse: -
array[i] = s.nextLine();
And, I think you should fill your array based on the input received from the file. Here you are receving input based on the length of your pre-declared array. I mean, since you are using an array, your size is fixed. So you can only populate it with a fixed number of phrases.
A better way would be to use an ArrayList.
List<String> phrases = new ArrayList<String>();
Now, you can populate your arraylist, based on the phrases you get from your file. You don't need to pre-define the size. It increases in size dynamically.
And to add phrases, you would do: -
phrases.add(s.nextLine());
With a while loop to read till EOF.
while (s.hasNextLine()) {
phrases.add(s.nextLine());
}
Since you don't know how many phrases you're likely to have (I suspect), I would populate an ArrayList<String> and convert it to an array using ArrayList.toArray() once you're done. I'd perhaps keep it as a Java collection, however, for greater flexibility.
You have the assignment operation inverted (array[i] should be set to s.nextLine(), not the other way around. Also, it would be best to modify the for loop to terminate when no more lines exist:
for(i = 0; i < array.length && s.hasNextLine() ;i++) {
array[i] = s.nextLine()
}
It can be done with a 1 liner with apache commons and specifically FileUtils.readLines()
FileUtils.readLines(myFile).toArray(new String[0]);
Don't waste your time with Scanner. BufferedReader is just fine. Try this:
BufferedReader br = new BufferedReader(new FileReader("Phrases.txt")));
LinkedList<String> phrases = new LinkedList<String>();
while(br.ready()) {
phrases.add(br.readLine());
}
String[] phraseArray = phrases.toArray(new String[0]);
By the way it's important to use LinkedList not ArrayList if the file is large. That way you only create one array at the end. Otherwise you will have a lot of large array creation and wasted memory.
you are doing it wrong. it has to be
for(i = 0; i < array.length;i++)
{
array[i]=s.nextLine();
}
array[i] = value; // the value would be assigned into the array at index i.
However, a better option would be to use a List implementing classes such as ArrayList which gives you an advantage of dynamic size.
List<String> list = new ArrayList<>();
list.add(s.nextLine(());

Java - Creating an Undefined Array

I'm looking to create an array that will be able to change size over time because the size of the array is unpredictable and I don't want to create a huge random number that will waste memory so every time a button is pressed I need the array to grow by one.
private String[][] lyricLineInfo = new String[x][5];
In the place of x is where the array must grow upon the button push and 5 is a constant. So I need the x button to grow by one without overflowing. Can I do it by using something like this?
lyricLineInfo[lyricLineInfo.length + 1][4] = fieldLyrics.getText();
Anyways thanks in advance!
Use an ArrayList<String[]> (see the docs here). It will grow automatically. (It uses an internal array that doesn't actually grow by just 1 when it needs to grow. Since growing is an expensive operation, it grows by some larger amount so it can absorb a few more items before having to grow again.)
EDIT
For example, here's how you could recode the two lines of your original post:
private ArrayList<String[]> lyricLineInfo = new ArrayList<String[]>();
lyricLineInfo.add(fieldLyrics.getText());
The second line assumes that fieldLyrics.getText() returns a String[]. If I misunderstood your intent and it returns a String, then you could do the following:
String[] nextStrings = new String[5];
nextStrings[4] = fieldLyrics.getText();
lyricLineInfo.add(nextStrings);
If the second index isn't always 5 long, you can also have an ArrayList of ArrayLists:
private ArrayList<ArrayList<String>> lyricLineInfo
= new ArrayList<ArrayList<String>>();
Then you could lyricLineInfo.add(new ArrayList<String>()); to extend the array.
EDIT 2
#clankfan1 - In your comment, you asked how to do a particular operation. Let's say we're using the ArrayList<ArrayList<String>> structure. It would go something like this:
ArrayList<ArrayList<String>> lyricLineInfo = new ArrayList<ArrayList<String>>();
ArrayList<String> line = new ArrayList<String>();
line.add("true");
line.add("true");
line.add("0.0");
line.add("5.0");
line.add("First Line");
lyricLineInfo.add(line);
line = new ArrayList<String>(); // don't use clear(): need a new object here
line.add("false");
line.add("false");
line.add("5.0");
line.add("10.0");
line.add("Second Line");
lyricLineInfo.add(line);
String secondLineTitle = lyricLineInfo.get(1).get(4); // will be "Second Line"
Obviously, this logic is amenable to being put into a separate method.
EDIT 3
If you need the elements of lyricLineInfo to be of type String[], it is vital that each element be a distinct array. Here are a few coding styles for adding elements:
ArrayList<String[]> lyricLineInfo = new ArrayList<String[]>();
String[] line = { "true", "true", "0.0", "5.0", "First Line" };
lyricLineInfo.add(line);
// now for a second style:
line = new String[5];
line[0] = "false";
line[1] = "false";
line[2] = "5.0";
line[3] = "10.0";
line[4] = "Second Line";
lyricLineInfo.add(line);
// and a third style:
lyricLineInfo.add(new String[] {
"false", "true", "10.0", "15.0", "Third Line"
});
String secondLineTitle = lyricLineInfo.get(1)[4]; // will be "Second Line"
You could use java.util.Vector<String[]>.
Use an ArrayList like this:
private ArrayList<ArrayList<String>> lyricLineInfo = new ArrayList<ArrayList<String>>();
ArrayLists are flexible arrays in java. When you want to add something do this:
lyricLineInfo.add(stringToBeAdded, index) //for the first dimension and
lyricLineInfo.get(firstIndex).add(stringToBeAdded, index); //for the second dimension
Use a List instead:
private List<String[]> lyricLineInfo = new ArrayList<String[]>();
Then to add to the list you use:
lyricLineInfo.add(new String[5]);
and to get you do:
// Get the 3rd element (array index 2).
String[] strings = lyricLineInfo.get(2);
Why don't you think about using Collections if you need an array with undefined size? :)
You can't do that with an array, but you can use a List object. You could try something like this:
private List<String[]> lyricLineInfo = new ArrayList<String[]>();
So then, assuming fieldLyrics.getText() returns a String[], you would do:
lyricLineInfo.add(fieldLyrics.getText());
If you only add new elements and iterate over all elements in list you should use LinkedList instead.
Collections are heavily used in Java. You should check Java Collections Framework - tutorial

Categories

Resources