I am trying to read from a file and add each line from the file to my array "Titles" but keep getting the error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
Any Ideas? I am getting the error because of the line reading:
Titles[lineNum] = m_line;
My code:
String[] Titles={};
int lineNum;
m_fileReader = new BufferedReader(new FileReader("random_nouns.txt"));
m_line = m_fileReader.readLine();
while (m_line != null)
{
Titles[lineNum] = m_line;
m_line = m_fileReader.readLine();
lineNum++;
}
Thank you in advance!
array indexes start with 0. if length of an array is N, then the last index would be N-1. currently your array has a length of zero and you are trying to access an element at index 0(which does exist).
String[] Titles={};//length zero
and in your while loop
Titles[lineNum] = m_line; //trying to access element at 0 index which doesnt exist.
I would suggest you use ArrayList instead of Array in your case. as ArrayList is dynamic (you dont have to give size for it)
List<String> titles = new ArrayList<String>();
while (m_line != null)
{
titles.add(m_line);
}
Array is not growable like ArrayList. Before you add element in string array you need to specify size of String[]
String titles[] = new String[total_lines] ;
or you can simply add each lines in ArrayList then finally convert into an Array like
int totalLineNumbers;
ArrayList<String> list = new ArrayList();
m_fileReader = new BufferedReader(new FileReader("random_nouns.txt")); m_line = m_fileReader.readLine();
while (m_line != null)
{
list.add(m_fileReader.readLine());
}
String titles[] = (String[]) list.toArray();
totalLineNumbers = titles.length ;
Related
This question already has answers here:
Why does my ArrayList contain N copies of the last item added to the list?
(5 answers)
Closed 6 years ago.
Okay so I have this two Lists called idadults and adults, I also have two String[] arrays called infoAdults (of size 255) and adultsID (of size 1). The code I have makes infoAdults read the information from a CSV file and adds that information to the adults list. It also checks if any value/box is missing, and changes its value to "9999". On column #15 in the CSV file, there's the id of each Adult, but some of them are missing. adultsID grabs each value of the column and then adds it to the idadults list. The code also first checks if that value exists, and if not it changes it to "9999" again.
My problem is that when I print the adults list it prints everything correctly like it should be, but when I try to print the idadults list it only prints the last value in the column over and over again n times, n being the size of the column. I already tried removing the "static" part when I define both of my Lists, but it didn't work. I also already tried to print adultsID[0] individually, and they all print correctly.
What do?
public String[] adultsID = new String[1];
public static List<String[]> idadults = new ArrayList<String[]>();
public static String csvFile = userDir + "/Adults.csv";
public String[] infoAdults = new String[255];
public static List<String[]> adults = new ArrayList<String[]>();
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
infoAdults = line.split(csvSplitBy);
for(int i=0;i<infoAdults.length;i++){
if(infoAdults[i].isEmpty()){
infoAdults[i]="9999";
}
if(i>16){
adultsID[0]=infoAdults[16];
}
else{
adultsID[0]="9999";
}
}
idadults.add(adultsID);
adults.add(infoAdults);
}
for (String[] strings : idadults) {
System.out.println(Arrays.toString(strings));
}
}
When you add adultsID to adults, you are adding the reference of adultsID.
Inside the while loop you are modifying only the data referenced by adultsID:
if(i>16){
adultsID[0]=infoAdults[16];
}
else{
adultsID[0]="9999";
}
And then you are adding the same reference to adults, on every iteration
idadults.add(adultsID);
So all the references point to same data which is modified every time the loop runs.
That is why you see only the last value reflected in all the list elements.
But for infoAdults , you are reassigning a new array to infoAdults everytime in the loop:
infoAdults = line.split(csvSplitBy);
So infoAdults refers to new data on every iteration.
Thus you add a new instance of infoAdults everytime in the list and all of them refer to different data
To get the expected output you can assign a new array to adultsID everytime in loop:
while ((line = br.readLine()) != null) {
infoAdults = line.split(csvSplitBy);
adultsID = new String[500];
for(int i=0;i<infoAdults.length;i++){
if(infoAdults[i].isEmpty()){
infoAdults[i]="9999";
}
if(i>16){
adultsID[0]=infoAdults[16];
}
else{
adultsID[0]="9999";
}
}
Lets say you have an array like this: String[] theWords = {"hello", "good bye", "tomorrow"}. I want to remove/ignore all the strings in the array that have the letter 'e'. How would I go about doing that? My thinking is to go:
for (int arrPos = 0; arrPos < theWords.length; arrPos++) { //Go through the array
for (int charPos = 0; charPos < theWords[arrPos].length(); charPos++) { //Go through the strings in the array
if (!((theWords[arrPos].charAt(charPos) == 'e')) { //Finds 'e' in the strings
//Put the words that don't have any 'e' into a new array;
//This is where I'm stuck
}
}
}
I'm not sure if my logic works and if I'm even on the right track. Any responses would be helpful. Many thanks.
One easy way to filter an array is to populate an ArrayList with if in a for-each loop:
List<String> noEs = new ArrayList<>();
for (String word : theWords) {
if (!word.contains("e")) {
noEs.add(word);
}
}
Another way in Java 8 is to use Collection#removeIf:
List<String> noEs = new ArrayList<>(Arrays.asList(theWords));
noEs.removeIf(word -> word.contains("e"));
Or use Stream#filter:
String[] noEs = Arrays.stream(theWords)
.filter(word -> !word.contains("e"))
.toArray(String[]::new);
You can directly use contains() method of String class to check if "e" is present in your string. That will save your extra for loop.
It would be simple if you use ArrayList.
importing import java.util.ArrayList;
ArrayList<String> theWords = new ArrayList<String>();
ArrayList<String> yourNewArray = new ArrayList<String>;//Initializing you new array
theWords.add("hello");
theWords.add("good bye");
theWords.add("tommorow");
for (int arrPos = 0; arrPos < theWords.size(); arrPos++) { //Go through the array
if(!theWords.get(arrPos).contains("e")){
yourNewArray.add(theWords.get(arrPos));// Adding non-e containing string into your new array
}
}
The problem you have is that you need to declare and instantiate the String array before you even know how many elements are going to be in it (since you wouldn't know how many strings would not contain 'e' before going through the loop).
Instead, if you use an ArrayList you do not need to know the required size beforehand. Here is my code from start to end.
String[] theWords = { "hello", "good bye", "tomorrow" };
//creating a new ArrayList object
ArrayList<String> myList = new ArrayList<String>();
//adding the corresponding array contents to the list.
//myList and theWords point to different locations in the memory.
for(String str : theWords) {
myList.add(str);
}
//create a new list containing the items you want to remove
ArrayList<String> removeFromList = new ArrayList<>();
for(String str : myList) {
if(str.contains("e")) {
removeFromList.add(str);
}
}
//now remove those items from the list
myList.removeAll(removeFromList);
//create a new Array based on the size of the list when the strings containing e is removed
//theWords now refers to this new Array.
theWords = new String[myList.size()];
//convert the list to the array
myList.toArray(theWords);
//now theWords array contains only the string(s) not containing 'e'
System.out.println(Arrays.toString(theWords));
I'm successfully getting the values from CSV file in to List<String[]>, but having problem in moving values from List<String[]> to String[] or to get single value from List. I want to copy these values in to string array to perform some functions on it.
My values are in scoreList
final List<String[]> scoreList = csvFile.read();
Now I want to get single value from this scoreList. I have tried this approaches but could not get the value
String[] value=scoreList.get(1);
You want a single value but you are declearing an array an you are tring to assign string to string array. If you want a single value, try this;
String x = scoreList.get(1);
or
if you want to convert listarray to string array try this;
String[] myArray = new String[scoreList.size()];
for(int i=0; i<scoreList.size();i++)
{
myArray[i]=scoreList.get(i);
}
Suppose you want to collect values of the 2nd column (index 1) then you can try this
// Collect values to this list.
List<String> scores = new ArrayList<String>();
final List<String[]> scoreList = csvFile.read();
// For each row in the csv file
for (String [] scoreRow : scoreList ) {
// var added here for readability. Get second column value
String value = scoreRow[1];
scores.add(value);
}
I am newbie to Java so if my question doesn't make sense then please suggest to improve it so that I get my question answered.
This is how, I am initializing arrays.
public static String[][] data = null;
String[] ReadValue= new String[3];
int p = 0;
I am reading element of CSV file and trying to put in a JTable. Below is code to feed to two dimensional array from CSV file. It throws NullPointerException error when I try to assign value to two dimensional array.
In Line - data[p][i] = ReadValue[i].trim();
My code:
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine())!= null) {
ReadValue= line.split(csvSplitBy);
for (int i = 0; i < ReadValue.length; i++){
data[p][i] = ReadValue[i].trim();
// System.out.println(""+ReadValue[i].toString());
}
p++;
}
Error:
java.lang.NullPointerException
at com.srinar.graphicsTest.JtableTest.LoadCSVdata(JtableTest.java:82)
JtableTest.java:82 : - data[p][i] = ReadValue[i].trim();
You must initialize your array by choosing the number of rows and columns you wish to store in it.
For example :
public static String[][] data = new String[rowNum][colNum];
So I gathered tokens from multiple lines of a text file and put those tokens into an array called tokens. With this code.
scanner = new Scanner(file);
while (scanner.hasNextLine()) {
if ((line = scanner.nextLine()).charAt(0) != '#') {
tokens = line.split(",");
}
}
(Its all in a try catch block)
I need to put all of those String tokens into a single array, how would I do this.
My new array is stringTokens [] = new String [countLines *4].
The while loop redefines the elements in tokens with each iteration, how do I save those old elements in stringTokens and add the new elements tokens will get into stringTokens as well.
You can use an ArrayList<String> for that, and when you need it as array, you can convert it to one:
ArrayList<String> list = new ArrayList<>();
scanner = new Scanner(file);
while (scanner.hasNextLine()) {
if ((line = scanner.nextLine()).charAt(0) != '#') {
for(String s : line.split(",")) {
list.add(s);
}
}
}
stringTokens = list.toArray(new String[0]);
You should look into using ArrayLists. They are essentially mutable arrays, with no specified size (the array "grows"* as you add elements.) and adding each token to your list of strings.
ArrayList<String> stringTokens = new ArrayList<String>();
...
for(String s : line.split(",")) {
stringTokens.add(s);
}
*Capacity doubles when needed.