I'm new to OOP, but I'm trying to create my first bigger program.
I've read a txt-file and stored the values (doubles) into an array, I call it originalArray. The text has two columns and 20 lines. So when I want to print the values in the first column of the txt-file I simply write:
System.out.println(originalArray[0]);
OUTPUT: 1991.00
300.50
498.50 .... et cetera...
My problem is that i'd like to use a for-loop (or whatever) to create two new arrays, each consisting one column from the "original array".
I thought it would be as simple as using a for-loop, like this;
double [] newArray = new double [20];
for(int i = 0; i < originalArray.length; i++){
newArray[i] = originalArray[0] //if I want to fill it with the first
//columns data... the second would be newArray2[i] = originalArray[1]
}
But this fills the new array with ONE element from the column in the originalArray... So - I need help to figure of how to write the loop to fill the new arrays with all elements from one chosen column.
Very grateful for help!
Regards/ frustrated newbie
EDIT: This is how I read the txt file:
String file = "C:\\Users\\komena\\Desktop\\30th-sales.csv";
BufferedReader br = null;
String line = "";
String splitBy = ";";
originalArray = new double [20];
br = new BufferedReader(new FileReader(file));
br.readLine();//skip the first line to get rid of header…
while ((line = br.readLine()) != null) {
String[] readlineArray = line.split(splitBy);
for (int i = 0; i < readlineArray.length; i++) {
originalArray[i] = Double.parseDouble(readlineArray[i]);
}
Whole text (csv) file:
300.50;330.00
489.50;296.50
34.50;399.50
900.00;1890.00
2052.00;568.00
354.00;0.00
399.00;0.00
1299.50;0.00
426.00;259.00
29.50;2300.50
99.50;349.50
2500.50;0.00
358.50;113.00
789.00;239.50
998.00;348.00
16.50;679.00
800.00;723.00
1899.50;950.50
550.50;568.00
Create the new 2D array with the size of the 1st dimension the same as the originalArray's length and the 2nd dimension the size of 2 (2 columns). Then simply loop it and add the old values to one column and also the new ones if reuqired, otherwise they will be set as 0.0 defaultly.
double originalArray[] = {1991.00, 300.50, 498.50};
double newArray[][] = new double[originalArray.length][2];
for (int i=0; i<originalArray.length; i++) {
newArray[i][0] = i // Fill the 1st column with sth like ID
newArray[i][1] = originalArray[i]; // Copy the 1D array to the 2nd column
}
System.out.println(Arrays.deepToString(newArray)); // Print all the array values
Output:
[[1.0, 1991.00],
[2.0, 300.50],
[3.0, 498.50]]
Moreover you read the file wrong. Notice that you have 2 values in the each line separated with ; and lines separated with \n. So read the line by line and add 2 values to the array.
The i variable represents the actual index of the originalArray[].
BufferedReader br = null;
String line = "";
int i=0;
double originalArray[] = new double[20];
br = new BufferedReader(new FileReader(file));
br.readLine();//skip the first line to get rid of header…
while ((line = br.readLine()) != null && i<originalArray.length) {
String[] readlineArray = line.split(";");
originalArray[i] = Double.parseDouble(readlineArray[0]);
originalArray[i+1] = Double.parseDouble(readlineArray[1]);
i+=2;
}
System.out.println(Arrays.toString(originalArray));
Related
I'm trying to read a text file and put each comma separated value in an array and put all of them inside a 2d array.But the code I have right now puts the whole line in the array
Scanner sc = new Scanner(new BufferedReader(new FileReader(path)));
int rows = 3;
int columns = 1;
String[][] myArray = new String[rows][columns];
while (sc.hasNextLine()) {
for (int i = 0; i < myArray.length; i++) {
String[] line = sc.nextLine().trim().split(" " + ",");
for (int j = 0; j < line.length; j++) {
myArray[i][j] = line[j];
}
}
}
System.out.println(Arrays.deepToString(myArray));
This is the text file:
A6,A7
F2,F3
F6,G6
Output
[[A6,A7], [F2,F3], [F6,G6]]
Expected Output
[[A6],[A7],[F2],[F3],[F6],[G6]]
The problem is that you are assigning the entire 2D array instead of just each item.
Here are several alternatives.
Use Files.lines to stream the file.
splitting on a comma creates the 1D array of two elements for each line
flatMap that to stream each item.
that map that to an array of one item.
then just store them in a 2D array.
String[][] array = null;
try {
array = Files.lines(Path.of("f:/MyInfo.txt"))
.flatMap(line->Arrays.stream(line.split(","))
.map(item->new String[]{item}))
.toArray(String[][]::new);
} catch (IOException ioe) {
ioe.printStackTrace();
}
if (array != null) {
System.out.println(Arrays.deepToString(array));
}
prints
[[A6], [A7], [F2], [F3], [F6], [G6]]
Here is an approach similar to yours.
List<String[]> list = new ArrayList<>();
try {
Scanner scanner = new Scanner(new File("f:/MyInfo.txt"));
while (scanner.hasNextLine()) {
String[] arr = scanner.nextLine().split(",");
for (String item : arr) {
list.add(new String[]{item});
}
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
There is no deepToString for Lists so you either iterate it or convert to a 2D array.
String[][] ar = list.toArray(String[][]::new);
System.out.println(Arrays.deepToString(ar));
prints
[[A6], [A7], [F2], [F3], [F6], [G6]]
i think you have to double the rows size and for each line just put one element and increment the i++
The declaration of the result array is not correct.
Since you want the end result should look like this, [[A6],[A7],[F2],[F3],[F6],[G6]], it is a 2-dimensional array with one row and six columns.
Considering it, I have changed and simplified your code.
int rows = 3;
String[][] r = new String[1][rows * 2];
FileInputStream fstream = new FileInputStream("/path/to/the/file")
BufferedReader br = new BufferedReader(new InputStreamReader(stream));
while((line = br.readLine()) != null) {
String[] current = line.split(",");
r[0][i++] = current[0];
r[0][i++] = current[1];
}
I am reading from a csv file called bookings which has 3 rows currently
1,000,Test Name,1,First
2,000,Another Name,2,First
3,001,Yet Another,3,Business
I have a method which is meant to read through the file and add each element into a 2d array of bookings, however, the method instead adds the same record to all elements in the 2d array
Output:
Bookings: [[3, 001, Yet Another, 3, Business], [3, 001, Yet Another, 3, Business], [3, 001, Yet Another, 3, Business]
Code:
public class Booker {
int flightsLength;
int nextFlight;
// 2D Array representing bookings
String[][] bookings = new String[1000][5];
// Read bookings from csvr
//file path
String path ="bookings.csv";
//current line being read
String line;
public void readBookings() {
try {
//new buffered reader object named br
BufferedReader br;
System.out.println("RUNNING:");
//initialise the buffered reader with the file as a parameter
br = new BufferedReader(new FileReader(path));
// Store length of flights csv
flightsLength = getFlightsCount();
//while next line is available, loop
while ((line = br.readLine()) != null) {
String[] values = line.split(",");
for (int row = 0; row < flightsLength; row++) {
for (int cell = 0; cell <= 4; cell++) {
bookings[row][cell] = values[cell];
}
}
}
System.out.println("Bookings: " + Arrays.deepToString(bookings));
System.out.println();
} catch (IOException e) {
e.printStackTrace();
}
}
Please let me know if I should explain the code more or if there is any confusion, and thank you in advance for the help.
You read each line, parse it, and then proceed to add its values to ALL the rows from 0 to flightsLength, every time.
Instead you need to read each line, parse it, and then add it to the next row in your bookings.
Effectively, get rid of the for (int row = 0; row < flightsLength; row++) { (and the matching }) that ruin things for you, and maintain your own row index, something like:
int row = 0;
//while next line is available, loop
while ((line = br.readLine()) != null) {
String[] values = line.split(",");
for (int cell = 0; cell <= 4; cell++) {
bookings[row][cell] = values[cell];
}
row++;
}
I have this CSV file:
World Development Indicators
Number of countries,4
Country Name,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014
Bangladesh,6.28776238,13.20573922,23.46762823,30.16828408,34.35334451,44.94535882,55.19256723,62.82023906,74.42964608,80.03535051
"Bahamas, The",69.21279415,75.37855087,109.340767,102.7875065,101.2186453,118.8292307,81.5628489,80.65383375,76.05187427,82.29635806
Brazil,46.31418452,53.11025849,63.67475185,78.5549801,87.54187651,100.8810115,119.0023853,125.0018521,135.3050481,138.9514906
Germany,94.55486999,102.2828888,115.1403608,126.5575074,126.2280577,106.4836959,109.6595675,111.5940398,120.9211651,120.4201855
I am trying to store countries' data(double once) into a matrix(double[][]). Here is the code that I have so far:
public double[][] getParsedTable() throws IOException {
double[][] table = new double[4][10];
String row;
int indexRow = 0;
int indexColumn = 0;
BufferedReader br = new BufferedReader(new FileReader(fileName));
br.readLine();
br.readLine();
String line = br.readLine();
while(line != null && !line.isEmpty()){
line = br.readLine();
String[] array = line.split(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)", -1);
for(int i = 1; i < array.length; i++){
table[indexRow][indexColumn] = Double.parseDouble(array[i]);
indexColumn++;
}
indexColumn = 0;
indexRow++;
}
System.out.print(Arrays.deepToString(table));
return table;
}
I am getting an arror : NullPointerException at:
String[] array = line.split(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)", -1);
I cant figure out why. I tried different combinations. nothing seems to work. It seems to pick up the numbers from the CSV file and store them, but when I call:
System.out.print(Arrays.deepToString(table));
it does not print out anything, hence I cant check if its stored properly or not. Could you tell me: 1. Why I am getting an error. 2. Why System.out.println does not print out an array. Thanks
If we assume that name of a country will not contain a digit and country name and numbers will be only comma separated, then following can be done without regex. I have changed file reading a little bit because it can run into issues.
public double[][] getParsedTable() throws IOException {
double[][] table = new double[4][10];
int indexRow = 0;
int indexColumn = 0;
BufferedReader br = new BufferedReader(new FileReader(fileName));
br.readLine(); // ignore first line
br.readLine(); // ignore second line
br.readLine(); // ignore third line (contains title)
String line;
while (true) {
line = br.readLine();
if (line == null) break; // end of file reading
int index = 0;
while (true) {
index = line.indexOf(",", index) + 1;
if (Character.isDigit(line.charAt(index))) {
break;
}
}
// from index, line is expected to contain comma separated numbers
String[] array = line.substring(index).split(",");
for (int i = 0; i < array.length; i++) {
table[indexRow][indexColumn] = Double.parseDouble(array[i]);
indexColumn++;
}
indexColumn = 0;
indexRow++;
}
System.out.print(Arrays.deepToString(table));
return table;
}
In the csv, first 3 lines are not real country's data. So read in line-4 before while loop starts.
In while loop, first finish the processing of line string first. Eg: regular expression check & assign split data into table.
Then only read in next line at end of while loop, to be processed in next iteration.
Feel free to try this out:
public double[][] getParsedTable() throws IOException {
double[][] table = new double[4][10];
int indexRow = 0;
int indexColumn = 0;
// check whether you need to handle any exception for this
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line = null;
try {
// line 1-3 are not real country's data
br.readLine();
br.readLine();
br.readLine();
// first country data begin at line 4
line = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
while (line != null && !line.isEmpty()) {
String[] array = line.split(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)", -1);
for (int i = 1; i < array.length; i++) {
table[indexRow][indexColumn] = Double.parseDouble(array[i]);
indexColumn++;
}
indexColumn = 0;
indexRow++;
// read next line only at end of loop, not beginning of loop
// line is ready to be processed at next iteration
try {
line = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.print(Arrays.deepToString(table));
return table;
}
Arrays.deepToString is wrong. You are passing in an array of primitives. When you pass it in, you pass in double[][]. This is interpeted as Object[] where the objects are double[], so it will try to print double[] objects, and not print doubles.
One solution is to create an array Double[][].
Change
double[][] table = new double[4][10];
to
Double[][] table = new Double[4][10];
Autoboxing will convert each double to a Double. Since Double is an object and not a primitive, deepToString will print out each Double individually. If you read the javadoc for deepToString it explains that it operates recursively on arrays of reference type, not on primitive arrays.
If you want to stick with double[][]
for (int i = 0; i < table.length; i++) {
for (int j = 0; j < table[i].length; j++) {
System.out.print(table[i][j]);
System.out.print(' ');
}
System.out.println();
}
I want to read a .txt file via a Java program.
Say this is the text file input.txt
abc, test, 1,2,3
abc
abcd
test, 1, 2, 3
Each line represents a row, each comma-separated value represents a column.
Currently my code is:
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
int num = readLines(); //this function just returns the number of lines
for (int i = 0; i < num; i++){
textData[i] = br.readLine();
}
br.close();
This outputs the text file as it was shown above if I print the array. But I require to insert into the array split by comma(could be other character as well, just use comma for now). So this means the output will be such that [abc,test,1,2,3],[abc],[abcd],[test,1,2,3] in the array. How should I proceed?
Thanks for the reply. Update:
Since i got my txt file into a array list,
[abc,test,1,2,3]
[abc]
[abcd]
[test,1,2,3]
How do i find the number of elements in each line?
Create an array list of array lists:
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
int lineCount = readLines();
ArrayList<ArrayList<String>> rows = new ArrayList<ArrayList<String>>(lineCount);
for (int i = 0; i < lineCount; i++) {
ArrayList<String> row = new ArrayList<String>();
String line = br.readLine();
for(String s: line.split(",")) {
row.add(s);
}
rows.add(row);
}
br.close();
I am writing some Java code to read each line of a data file into an array list, shuffle that list, and then perform some further operations on the shuffled data. The problem is that, after shuffling, I am getting null elements for some of the elements in the array list.
//this file contains the data
String input = ...;
//this file contains the number of rows in the data file
String input2 = ...;
FileInputStream fstream2 = new FileInputStream(input2);
DataInputStream in2 = new DataInputStream(fstream2);
BufferedReader brIndex = new BufferedReader(new InputStreamReader(in2));
for(int i = 1; i <= N; i++) {
FileInputStream fstream = new FileInputStream(input+(i+1)+".txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader brData = new BufferedReader(new InputStreamReader(in));
num = Integer.parseInt(brIndex.readLine());
ArrayList<String> temp = new ArrayList<String>();
for(int j = 0; j < num; j++) {
temp.add(brData.readLine());
}
brData.close();
Collections.shuffle(temp);
//read in shuffled data
for(int j = 0; j < num; j++) {
rowData = temp.get(j); ...
}
In executing the code, I get a NullPointerException after this when working with rowData. The original file has 17,169 rows (none of them are null). temp.size() is also 17,169 but when I printed temp out to the console, temp.get(j) was null for some j and not for others.
Can anyone explain to me why this is the case and how to avoid it?
The problem might be there are not enough lines in the file as num.
Try:
List<String> temp = new ArrayList<String>();
String line;
while((line = br.readLine()) != null) {
temp.add(brData.readLine());
}
You could also check for null elements in the list before you actually shuffle the list, as shuffle does not insert any new element to the list.
You never check if readLine() returns null or not. Check it, and you'll discover that you probably read past the end of the file.
Also, readers, writers and streams should always be closed in a finally block.