I have had a look at other posts, but I am still stuck on this issue for a while now. I have a text file that has various new lines, each of different length. I want to store them in a 2d array so that I can call specific locations i.e. word[1][4].
I've managed to store them in an array - my code is below. Thanks for your help!
String line = null;
ClassToRead txtFile = new ClassToRead("test.txt"); //reading using bufferReader
String [][] words = new String[txtFile.readLines()][]; //this is where I want to store the words
while( (line = br.readLine())!= null ){
String [] newData = line.split("\\s+");
System.out.println(Arrays.toString(newData)); //prints out array
}
//I want to use specific locations in the 2d array e.g. System.out.println(words[3][5]);
Try to add the arrays to the 2d array... you could use a counter like in the example bellow.
int counter = 0;
while( (line = br.readLine())!= null ){
String[] newData = line.split("\\s+");
words[counter] = newData;
counter++;
System.out.println(Arrays.toString(newData)); //prints out array
}
Related
I am a beginner in java and i am trying to make a program that partly requires for all the info from the CSV files to be stored into arrays. The CSV file only contains strings and has 23 rows and 3 columns. My problem is that i cannot find a way of storing everything since the array only stores the info from the last row, overwriting all the other rows.
'''
public static void main(String[] args) throws FileNotFoundException{
String[] StringPart=null;
File csvfile = new File("FileExample");
Scanner dodo = new Scanner(csvfile);
while(dodo.hasNextLine()){
String x = dodo.nextLine();
StringPart= x.split(",");
}
System.out.println(StringPart[0]+StringPart[1]+StringPart[2]);
'''
You are doing wrong in this line of code StringPart= x.split(",");. Here you are assigning again and again new values to StringPart. Try to add values to the array of string StringPart.
Since you have columns and rows, a 2d array is an appropriate representation. 2d arrays are an array of arrays. The outer array contains each row, the inner arrays contain each value.
The Files and Paths utility classes are from java.nio.file.*.
public static void main(String[] args) throws Exception {
// read file and store contents as String
File file = new File("csv_example.txt");
byte[] fileData = Files.readAllBytes(Paths.get(file.getAbsolutePath()));
String fileContent = new String(fileData);
String[][] values; // declare values
String[] lines = fileContent.split("\n"); // split files in to lines
values = new String[lines.length][]; // make values large enough to hold all lines
// for each line, add its values to an array in the 2d values array
for(int i = 0; i < lines.length; i++)
{
values[i] = lines[i].split(",");
}
}
In java 8, we can easily achieve it
BufferedReader br = new BufferedReader(new FileReader("test.csv"));
List<List<String>> dataList = br.lines()
.filter(line -> line.length()>0) //ignoring empty lines
.map(k -> Arrays.asList(k.split(",",-1))) // ,9346,Bharathi, -for this i should get [null,9346,Bharathi,null]
.collect(Collectors.toCollection(LinkedList::new));
outer list will have rows and inner list will have corresponding column values
I keep getting this Array out of bounds error for the following code.
brock.txt = reflection program, routine, Arrow, snake game,
public static void main(String[] args) {
String filename = "brock.txt";
String line;
String [] cities = {};
int x = 0;
try {
BufferedReader eshread = new BufferedReader( new FileReader (filename));
line = "";
while ((line = eshread.readLine()) != null ) {
String[] store = line.split(",");
System.out.println(store[0]);
System.out.println(store[1]);
System.out.println(store[2]);
cities[x] = store[2]; //< keep getting an error here
x++;
}//end while loop
eshread.close();
}//end try
catch(IOException iox) {
System.out.println("failiure");
}//end catch
String [] cities = {} will make the array size to 0,when x is greater than 0 the error will occur,that's the reason,so you need to make cities a fixed size at first or use List to do it
You Must define the size of cities or use a list .
You initialized cities with an empty array({}), which means it has a length of 0(not an null, but an empty array). By using cities[0] you are expecting it has at least one element, which is not true.
To fix this, use an ArrayList<String> instead of a String array.
In agreement with the other comments. The issue is with the size of cities array which is being set to 0 and hence the issue for array out of bounds.
I tried the following code and it works if you want to work with a String array.
Else an ArrayList is a better solution if the size is not defined.
String [] cities = new String[10];
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 a class "car", having five parametres of car (str brand, str model, str colour, int power, int tank), and I have a .txt with five cars, written like that:
Toyota Supra Black 280 80
Ferrari F430 Red 510 95
Nissan GT-R White 600 71
Koenigsegg Agera White 940 80
Mazda RX-8 Red 231 62
I have to read this list from file and make an array of lines array (cars), while each car array is an array of 5 parametres, like:
Cars[car][parametres], and push it into a object of a class (should be a peace of cake, and i think i can handle this)
But i have no clue how to deal with array. Only thing i have now is reading from file:
void 123() {
String[] ImpData = null;
try {
String str;
BufferedReader br = new BufferedReader(new FileReader("imp.txt"));
while ((str = br.readLine()) != null) {
System.out.println(str);
}
br.close();
} catch (IOException exc) {
System.out.println("IO error!" + exc);
}
}
Any suggestions?
Create a list of Car object and adding each line into the list as 1 Car object each.
ArrayList<Car> list = new ArrayList<Car>();
while ((str = br.readLine()) != null) { //Not checking your loop
String[] tok = str.split(" "); //str holds all car information
list.add(new Car(tok[0], tok[1], tok[2], tok[3], tok[4]));
}
Assuming your Car class has a constructor which accepts the 5 arguments.
Edit: (To fit requirement of using Array)
When you use array, you have to pre-allocate a fixed array length first. Using array is not suitable for storing data from files because there can exist any number of lines of data. Anyway, to answer your question on using array:
String[][] data = new String[numRecords][5]; //numRecords equals total car objects
int x=0;
while ((str = br.readLine()) != null) { //Not checking your loop
String[] tok = str.split(" "); //str holds all car information
data[x] = tok; //Assign entire row of tok into data
x++;
}
Once again, I seriously do not recommend reading data file into an array. If you really have to do so, you can pre-determine number of records in the text file first, then set the array size accordingly.
Side note: 2D arrays are also not a suitable data structure for storing data such as a car object with its own attributes.
You want a two dimensional array. However, note that the array size must be known in advance and you don't know how many lines are in the file. So, first read everything into a secondary linked list data structure (you could also read the file twice, this is not efficient). Now you have all the strings, make a two dimensional array and then split each string into an array of tokens, using the " " delimiter. If you want to treat the tokens as integers and strings, you can use an array of Object instead and store Integer, String, etc. Off the top of my head, something like this follows - also note in your post, you can't start a method with numbers :)
String[] ImpData = null;
try {
String str;
List<String> allStrings = new LinkedList<String>();
BufferedReader br = new BufferedReader(new FileReader("imp.txt"));
while ((str = br.readLine()) != null) {
allStrings.add(str);
}
br.close();
String[][] ImpData = new String[allStrings.size()][];
for(int i=0; i<allStrings.size();i++){
ImpData[i] = allStrings.get(i).split(" ");
}
} catch (IOException exc) {
System.out.println("IO error!" + exc);
}
I think what you are looking for is a 2-dimensional array.
The first dimension is the index for the car, the second are the 5 pieces that make it up. It looks like this: (not actual language, just a guide to build it.)
array is car[int][string, string, string, int, int]
car[0][Toyota,Supra,Black,280,80]
car[1][Ferrari,F430,Red,510,95]
So, referencing car[1] will tell you all about that car.
That's one idea, anyway...
for Car
class Car {
public String brand, model, colour;
int power, int tank;
}
structure
List<Car> cars = new ArrayLis<Car>()'
the most important part is safe analize line and fill part of data. The simplest (but not the best) is:
In out loop when You have line str line by line, set analyse:
String arg[] = str.split(" ");
Car c = new Car();
c.brand = arg[0];
c,model = arg[1];
c.color = arg[2];
c.power = Integer.parseInt(arg[3],0);
c.tank = Integer.parseInt(arg[4],0);
and then
cars.Add(c);
I am new to Java. How can i read each integer from a line in a text file. I know the reader class has the read and readline functions for it. But in my case i not only want to read the integers in the file but want to know when the line changes. Because the first element of every line denotes an array index and all the corresponding elements are the linked list values attached to that index.
For example, see the 4 line below. In this case i not only want to read each integer but the first integer of every line would be an array index so i will have an a 4 element array with each array element correspoding to a list where A[1]-> 4, A[2]-> 1,3,4 and soo on.
1 4
2 1 3 4
3 2 5
4 2
After retrieving the integers properly i am planning to populate them via
ArrayList<Integer>[] aList = (ArrayList<Integer>[]) new ArrayList[numLines];
EDITED : I had been asked in one the comments that what i have thinked soo far and where exctly i am stucken so below is what i am thinking (in terms of original and pseoudo code mixed)..
while (lr.readLine() != null) {
while ( // loop through each character)
if ( first charcter)
aList[index] = first character;
else
aList[index]->add(second char.... last char of the line);
}
Thanks
Thanks for the scanner hint, Andrew Thompson.
This is how i have achieved it
Scanner sc =new Scanner(new File("FileName.txt"));
ArrayList<Integer>[] aList = (ArrayList<Integer>[]) new ArrayList[200];
String line;
sc.useDelimiter("\\n");
int vertex = 0;
while (sc.hasNextLine()) {
int edge = 0;
line = sc.nextLine();
Scanner lineSc = new Scanner(line);
lineSc.useDelimiter("\\s");
vertex = lineSc.nextInt() - 1;
aList[vertex] = new ArrayList<Integer>();
int tmp = 0;
System.out.println(vertex);
while (lineSc.hasNextInt()) {
edge = lineSc.nextInt();
aList[vertex].add(edge);
System.out.print(aList[vertex].get(tmp) + " ");
++tmp;
}
System.out.println ();
}