Loading a CSV into multidimensional array - java

So what i need to do is load a csv file to a JTable with dynamic array(anywhere between 2 and 6 values), first i came up with this solution:
private String[][] Load()
{
try {
final BufferedReader br = new BufferedReader(new FileReader("FilePath");
try{
String line;
final ArrayList<String> List1 = new ArrayList<String>();
final ArrayList<String> List2 = new ArrayList<String>();
final ArrayList<String> List3 = new ArrayList<String>();
while((line = br.readLine()) != null)
{
final String[] parse = line.split(",");
List1.add(parse[0]);
List2.add(parse[1]);
List3.add(parse[2]);
}
final ArrayList[] lists = new ArrayList[]{List1, List2, List3};
final String[][] temp = new String[List1.size()][List1.get(0).split(",").length];
for(int x = 0 ; x < temp.length ; x++)
{
for(int y = 0 ; y < temp[x].length ; y++)
{
temp[x][y] = (String) lists[y].get(x);
}
}
return temp;
}finally
{
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
which i thought was horrible, so i came up with this solution:
private String[][] Load()
{
try
{
final BufferedReader br = new BufferedReader(new FileReader("FilePath"));
try
{
final List<String> raw = new ArrayList<String>();
String line;
while((line = br.readLine()) != null)
raw.add(line);
final String[][] temp = new String[raw.size()][raw.get(0).split(",").length];
for(int x = 0 ; x < raw.size() ; x++)
{
final String[] parse = raw.get(x).split(",");
for(int y = 0 ; y < temp[x].length ; y++)
{
temp[x][y] = parse[y];
}
}
return temp;
}finally
{
br.close();
}
}catch(IOException e){
e.printStackTrace();
}
return null;
}
but i'm not so sure about that either, both of them work just fine so really all i'm asking is, how would you do it?
Edit: can't really use external libs with this project.

Related

Array Index Out of Bounds Exception - CSV Import

I'm trying to import a CSV in a java program to a 2d array. Every time I test to see if it's been imported correctly it returns the correct result but also throws an Array Index Out of Bounds Exception (Index 45 out of bounds for length 45)
Here is the code and I appreciate any assistance.
public static String[][] readIn(String file){
BufferedReader reader1 = null;
BufferedReader reader2 = null;
String line = "";
int colCount = 0;
int maxLen = 0;
String[][] source = null;
try {
reader1 = new BufferedReader(new FileReader(file));
while((line = reader1.readLine()) != null) {
colCount++;
String[] row = line.split(",");
if (maxLen < row.length) {
maxLen = row.length;
}
else {}
}
source = new String[colCount][maxLen];
reader2 = new BufferedReader(new FileReader(file));
for(int x = 0; x < colCount; x++) {
line = reader2.readLine();
String[] row = line.split(",");
for (int y = 0; y < maxLen; y++) {
source[x][y]=row[y];
}
}
}
catch(Exception e) {
e.printStackTrace();
}
finally {
try {
reader1.close();
reader2.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return source;
}

incompatible types: String[] cannot be converted to String

I'm being completely beaten up by types in Java.
I have coordinates in a txt file, which ultimately I want to format into an array of these co-ordinates, with each array item being a double.
Each line of my txt file looks like so:
13.716 , 6.576600074768066
Currently, I'm trying to split this line into an array of two Strings, which I will then try and parse into doubles, but I keep getting the error in the title. Where am I going wrong?
Any other better approaches on converting my Arraylist of Strings to a formatted list of double coordinates would be great, like so
[[0,1], [0,2], 0,4]
Code:
public static String[] getFileContents(String path) throws FileNotFoundException, IOException
{
InputStream in = new FileInputStream(new File(path));
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
List<String> data = new ArrayList<String>();
StringBuilder out = new StringBuilder();
String line;
// Skips 1376 characters before accessing data
reader.skip(1378);
while ((line = reader.readLine()) != null) {
data.add(line);
// System.out.println(line);
}
for (int i=0; i < data.size(); i++){
data.set(i, data.get(i).split(","));
}
// String[] dataArr = data.toArray(new String[data.size()]);
// Test that dataArr[0] is correct
// System.out.println(data.size());
// List<String> formattedData = new ArrayList<String>();
// for (int i = 0; i < data.size(); i++){
// formattedData.add(dataArr[i].split(","));
// }
reader.close();
return dataArr;
}
The split(",") method return array of string string[] and you can't set string by array of string.
Crate point class with let lan double variabels and then create array of this point and them fill them with data from reading each line:
class Point{
double lat;
double len;
Point(double lat, double len){
this.lat = lat;
this.len = len;
}
}
And then use this class in your code:
public static String[] getFileContents(String path) throws FileNotFoundException, IOException
{
InputStream in = new FileInputStream(new File(path));
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
List<String> data = new ArrayList<String>();
StringBuilder out = new StringBuilder();
String line;
// Skips 1376 characters before accessing data
reader.skip(1378);
while ((line = reader.readLine()) != null) {
data.add(line);
// System.out.println(line);
}
List<Point> points = new ArrayList<Point>();
for (int i=0; i < data.size(); i++){
double lat = Double.parseDouble(data.get(i).split(",")[0]);
double len = Double.parseDouble(data.get(i).split(",")[1]);
points.add(new Point(lat, len));
//data.set(i, data.get(i).split(","));
}
// String[] dataArr = data.toArray(new String[data.size()]);
// Test that dataArr[0] is correct
// System.out.println(data.size());
// List<String> formattedData = new ArrayList<String>();
// for (int i = 0; i < data.size(); i++){
// formattedData.add(dataArr[i].split(","));
// }
reader.close();
return dataArr;
}
you can update your while loop like this
while ((line = reader.readLine()) != null) {
String[] splits = line.split(",");
for(String s : splits) {
data.add(s);
}
}

How to subtract values of two lists/arrays in Java?

I am working on a Java project and I am having a problem. I want to have the subtract of two lists or arrays a and b in list/array c but I don't know how to do that. I want "a[i] -b[i]" should be in next list c where the value should be c[i] similarly for 5-2=3 any suggestion and help would be appreciated.
Code:
public static void länge() {
{
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(new File("C:\\Users/Voodoothechild/Desktop/Pidata/Anfang.txt")));
String line = null;
while ((line = br.readLine()) != null) {
{
BufferedReader bro = null;
try {
bro = new BufferedReader(new FileReader(new File("C:\\Users/Voodoothechild/Desktop/Pidata/Ende.txt")));
String lines = null;
while ((lines = br.readLine()) != null) {
String[] anfang = line.split("\n");
String[] ende = lines.split("\n");
List<Integer> an = new ArrayList<Integer>();
List<Integer> en = new ArrayList<Integer>();
for (int index = 0 ; index<ende.length ; index++) {
an.add(Integer.parseInt(anfang[index]));
en.add(Integer.parseInt(ende[index]));
Integer[] anf = new Integer[an.size()];
int[] result = new int[anf.length];
for (int i = 0; i < result.length; i++) {
result[i] = anf[i] - end[i];
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bro != null) {
try {
bro.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
} catch(FileNotFoundException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
}
}
It can be done easily using Stream API:
int[] list1 = {4,2,1};
int[] list2 = {2,2,-1};
IntStream.range(0, list1.length)
.mapToObj(i -> list1[i] - list2[i])
.collect(Collectors.toList());
or even easier using Javaslang:
Stream.range(0, list1.length)
map(i -> list1[i] - list2[i]);
or by zipping two lists together:
List.ofAll(list1)
.zip(List.ofAll(list2))
.map(t -> t._1 - t._2);
Its pretty straight forward. Before tackling a programming problem. Always do it in steps. Take your problem for example. You need to subtract values from 2 arrays with values.
int[] list1 = {4,2,1};
int[] list2 = {2,2,-1};
Now you have 2 list. Ok next step, write a loop to go through the list. But first make sure that both list have the same length or else you will get an index out of bounce.
for(int i =0; i< list1.length; i++)
{
list3[i] = list1[i] - list2[i];
}
Anyway here is the full answer. Be sure to understand it
public class subtract
{
public static void main(String[] args)
{
int[] list1 = {4,2,1};
int[] list2 = {2,2,-1};
int[] list3 = new int[list1.length];
//Looping the list
for(int i =0; i< list1.length; i++)
{
list3[i] = list1[i] - list2[i];
}
//Print Statement
for(int j =0; j< list3.length; j++)
{
System.out.println(list3[j]);
}
}
}
Here's a very simple answer you can apply to your program.
public static void main(String[] args) {
int[] a = new int[4];
int[] b = new int[4];
int[] c = new int[4];
a[0] = 5;
a[1] = 12;
a[2] = 20;
a[3] = 50;
b[0] = 1;
b[1] = 2;
b[2] = 3;
b[3] = 4;
for(int i=0; i<a.length; i++){
c[i] = a[i] - b[i];
System.out.println(c[i]);
}
}
The answer is the method removeAll of class Collection
ArrayList<Integer> s1 = new ArrayList<Integer>(Arrays.asList(a1));
ArrayList<Integer> s2 = new ArrayList<Integer>(Arrays.asList(a2));
s1.removeAll(s2);
Integer[] result = s1.toArray(new Integer[s1.size()]);

Java - Splitting ArrayList

Hello all I am trying to scan the bottom 6 lines of a text file and display them in a JOptionPane.showMessageDialog currently it is being displayed as [line7, line6, line5, line4, line3, line2] I would prefer it to be displayed as a vertical list instead of the comma seperator.
ArrayList<String> bandWidth = new ArrayList<String>();
FileInputStream in = null;
try {
in = new FileInputStream("src/list.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String tmp;
try {
while ((tmp = br.readLine()) != null)
{
bandWidth.add(tmp);
if (bandWidth.size() == 7)
bandWidth.remove(0);
}
} catch (IOException e) {
e.printStackTrace();
}
ArrayList<String> reversedSix = new ArrayList<String>();
for (int i = bandWidth.size() - 1; i >= 0; i--)
reversedSix.add(bandWidth.get(i));
JOptionPane.showMessageDialog(null,bandWidth,null,JOptionPane.INFORMATION_MESSAGE);
Try looping the ArrayList and produce a String with new line characters:
String result = "";
for (int i = 0; i < bandWidth.size(); i++)
{
result += bandWidth.get(i) + "\n";
}
JOptionPane.showMessageDialog(null,result ,null,JOptionPane.INFORMATION_MESSAGE);
Note: if this is outputting HTML, then use <br \> instead of \n.

converting a string array to a double array

I am trying to convert a list of numbers from a txt file into an array of numbers. There is 26 numbers, and each is on a different line in the text file. My code is
import java.io.*;
public class rocket {
public static void main(String[] args) throws IOException, FileNotFoundException
{
BufferedReader b = new BufferedReader(new InputStreamReader(new FileInputStream("/Users/Jeremy/Documents/workspace/altitude.txt")));
String[] stringArray = new String[25];
double[] doubleArray = new double[stringArray.length];
for(int i=0; i<25; i++)
{
stringArray[i] = b.readLine();
doubleArray[i] = Double.parseDouble(stringArray[i]);
}
for(int i = 0; i<doubleArray.length; i++)
{
System.out.println(doubleArray[i]);
}
}
}
But every time I run it I get a number format exception. And if I try to just print out the strings I get an indexOutOfBounds exception
in question you have mentioned that there is 26 strings so declate
String[] stringArray = new String[26];
And The number format exception is occuring as readline returns with the linbreak. To read line you can do the following
public String[] readLines(String filename) throws IOException {
FileReader fileReader = new FileReader(filename);
BufferedReader bufferedReader = new BufferedReader(fileReader);
List<String> lines = new ArrayList<String>();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
lines.add(line);
}
bufferedReader.close();
return lines.toArray(new String[lines.size()]);
}
So by this logic you can get double by
public static Double[] readLines(String filename) throws IOException {
FileReader fileReader = new FileReader(filename);
BufferedReader bufferedReader = new BufferedReader(fileReader);
List<Double> lines = new ArrayList<Double>();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
lines.add(Double.parseDouble(line));
}
bufferedReader.close();
return lines.toArray(new Double[lines.size()]);
}
Try
BufferedReader b = new BufferedReader(
new InputStreamReader(
new FileInputStream(
"D:/git-repo/general/misc_test/src/java/com/greytip/cougar/module/test/v2/controller/so/dump/data.txt")));
List<String> lines = new ArrayList<String>();
String line = null;
while ((line = b.readLine()) != null) {
lines.add(line);
}
String[] stringArray = lines.toArray(new String[lines.size()]);
double[] doubleArray = new double[stringArray.length];
for (int i = 0; i < stringArray.length; i++) {
doubleArray[i] = Double.parseDouble(stringArray[i]);
}
for (int i = 0; i < doubleArray.length; i++) {
System.out.println(doubleArray[i]);
}
String[] stringArray = new String[26];
try this
import java.io.*;
public class Rocket {
public static void main(String[] args) throws IOException, FileNotFoundException
{
BufferedReader b = new BufferedReader(new InputStreamReader(new FileInputStream("/Users/Jeremy/Documents/workspace/altitude.txt")));
String[] stringArray = new String[25];
double[] doubleArray = new double[stringArray.length];
for(int i=0; i<25; i++)
{
stringArray[i] = b.readLine();
try{
doubleArray[i] = Double.parseDouble(stringArray[i]);
}catch(Exception e)
{
e.printStackTrace();
}
}
for(int i = 0; i<doubleArray.length; i++)
{
System.out.println(doubleArray[i]);
}
}
}
Handle the Exception when parse a string to double please.

Categories

Resources