I'm trying to load a CSV file into a 2d array, but when I go to call it in main I receive the error
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
In my code while the file has a next line, it splits up the line, stores it in a string array which will in turn be moved to the 2D array. I don't understand how there can be an error. Anyone willing to explain or am I just very dense?
public int rows = 0;
public int cols = 0;
public String[][] filetable = new String[rows][cols];
public void set_Array(File example)
{
try
{
FileReader file = new FileReader(example);
Scanner sc = new Scanner(file);
if(sc.hasNextLine())
{
String[] tokens = sc.nextLine().split(",");
cols = tokens.length;
rows++;
}
while(sc.hasNextLine())
{
rows++;
sc.nextLine();
}
}
catch (FileNotFoundException e)
{
System.out.println(e);
}
}
public void to_Array(File example)
{
try
{
FileReader file = new FileReader(example);
Scanner sc = new Scanner(file);
int r = 0;
while(sc.hasNextLine())
{
String[] tokens = sc.nextLine().split(",");
for(int c = 0; c < cols; c++)
{filetable[r][c] = tokens[c];}
r++;
}
}
catch (FileNotFoundException e)
{
System.out.println(e);
}
}
I don't know in which order you are calling set_Array and to_Array methods. But I guess, the problem is that you are essentially creating a 2D array of 0 rows and 0 sizes as public String[][] filetable = new String[rows][cols]; is called when rows=0 and cols=0. To rectify, call your set_Array method to assign proper values to rows and cols and then instantiate your 2D array inside your to_Array method.
public void to_Array(File example)
{// Now rows and cols will have proper values assigned
String[][] filetable = new String[rows][cols];
try
{
FileReader file = new FileReader(example);
Scanner sc = new Scanner(file);
int r = 0;
while(sc.hasNextLine())
{
String[] tokens = sc.nextLine().split(",");
for(int c = 0; c < cols; c++)
{filetable[r][c] = tokens[c];}
r++;
}
}
catch (FileNotFoundException e)
{
System.out.println(e);
}
}
Related
im making a word search program, the grid is 10 x 10 and all the letters are in a Char[][] array.
There is a words list too.
public static void find(){
Scanner input = null;
try {
input = new Scanner(new File(WORD_FILE));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
List<String> words = new ArrayList<>();
while (input.hasNextLine()){
words.add( input.nextLine());
}
input.close();
initgrid();
for (char[] a : grid){
String c =String.valueOf(a);
for (String s : words){
if (s.contains(c)){
// what can i do now?
}
}
}
Does anyone have any suggestions to how i can make the program iterate through each letter of the grid, and look for the words from the word list...it should be able to read words horizontally, vertically and diagonally.
here is my InitGrid() method which opens the grid file and assigns each character to a char[][] array.
public static char[][] initGrid(){
Scanner input = null;
try {
input = new Scanner(new File(GRID_FILE));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String[] tmp = new String[10];
int c = 0;
while (input.hasNextLine()){
tmp[c++]=input.nextLine();
}
input.close();
for (int b = 0; b<tmp.length;b++){
for (int j= 0; j<tmp[b].length();j++){
grid[b][j] = tmp[b].charAt(j);
}
}
return grid;
All the examples that i have seen involve specifying the number of rows and columns at the start of the file but the method I'm working on reads a file with the following:
1.0 2.0
3.0 4.0
and using this data creates a 2d array and stores it without specifying the number of rows and columns.
Here's the code I have written:
public static double[][] readMatrixFrom(String file) throws FileNotFoundException {
Scanner input = new Scanner(new FileReader(file));
int rows =0;
int columns =0;
while(input.hasNextLine()){
String line = input.nextLine();
rows++;
columns = line.length();
}
double[][] d = new double[rows][columns]
return d;
}
I'm unsure of how to add these values now that I have created the 2d array. i tried this but got an InputMismatchException.
Scanner s1 = new Scanner(file);
double[][] d = new double[rows][columns]
for (int i= 0;i<rows;i++) {
for (int j= 0;i<rows;j++) {
d[i][j] = s1.nextDouble();
}
}
if you just want to use the basic arrays you can achieve it with something like
Scanner input = new Scanner(new FileReader(file));
int row=0;
int col =0;
String s="";
//count number of rows
while(input.hasNextLine()) {
row++;
s=input.nextLine();
}
//count number of columns
for(char c: s.toCharArray()) {
if(c==' ')
col++;
}
col++; // since columns is one greater than the number of spaces
//close the file
input.close();
// and open it again to start reading it from the begining
input = new Scanner(new FileReader(file));
//declare a new array
double[][] d = new double[row][col];
int rowNum=0;
while(input.hasNextLine()) {
for(int i=0; i< col; i++) {
d[rowNum][i]= input.nextDouble();
}
rowNum++;
}
However if you prefer to use java collection you can avoid reading the file again. Just store the strings in a list and iterate over the list to extract elements from it.
Based on your input, Your columns = line.length(); is returning 7 rather than 2 as it returns the String length.
Hence try calculating the no of columns in the row columns = line.split(" ").length;
Also while trying to read your input you were using index i for the 2nd for-loop. It should be like below,
for (int i= 0;i<rows;i++) {
for (int j= 0;j<columns;j++) {
d[i][j] = s1.nextDouble();
}
}
In order to work with arrays of unknown size you should read the data into a Collection (such as a List). However, Collection(s) only work with the wrapper-types; so you will need to copy the elements back into an array of double(s) if that is what you really need. Something like,
public static double[][] readMatrixFrom(String file) throws FileNotFoundException {
Scanner input = new Scanner(new FileReader(file));
List<List<Double>> al = new ArrayList<>();
while (input.hasNextLine()) {
String line = input.nextLine();
List<Double> ll = new ArrayList<>();
Scanner sc = new Scanner(line);
while (sc.hasNextDouble()) {
ll.add(sc.nextDouble());
}
al.add(ll);
}
double[][] d = new double[al.size()][];
for (int i = 0; i < al.size(); i++) {
List<Double> list = al.get(i);
d[i] = new double[list.size()];
for (int j = 0; j < d[i].length; j++) {
d[i][j] = list.get(j);
}
}
return d;
}
Which I tested by creating a file in my home folder with your contents and running it like so
public static void main(String[] args) {
String file = System.getProperty("user.home") + File.separator + "temp.txt";
try {
System.out.println(Arrays.deepToString(readMatrixFrom(file)));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
And I get (as I assume you wanted)
[[1.0, 2.0], [3.0, 4.0]]
Working on an assignement where I have to read a .txt file and place it into a 2D array as is. Note ts HAS TO BE A 2D ARRAY.
I then have to print it like it is again.
The .txt input looks like this:
WWWSWWWW\n
WWW_WWWW\n
W___WWWW\n
__WWWWWW\n
W______W\n
WWWWWWEW\n
Here's the code I have currently, I have an error that says that it cannot resolve method 'add'. Probably has to do with the array initializer
public static void main(String[] args) throws FileNotFoundException {
Scanner s = new Scanner(new File("D:/trabalho/maze.txt"));
String[][] list = new list[][];
while (s.hasNextLine()){
list.add(s.nextLine());
}
s.close();
System.out.println(list);
}
Then the print output has to be
WWWSWWWW
WWW_WWWW
W___WWWW
__WWWWWW
W______W
WWWWWWEW
Any help? Thanks!
Assuming the reason for using 2D array is that each character is saved in a separate String object.
In case we know absolutely nothing regarding the text file, I would implement like this:
public static void main(String[] args) throws FileNotFoundException {
File textFile = new File("D:/trabalho/maze.txt");
Scanner rowsCounter = new Scanner(textFile));
int rows=0;
while (rowsCounter.hasNextLine()) {
rowsCounter.nextLine();
rows++;
}
String[][] data = new String[rows][];
Scanner reader = new Scanner(textFile);
for (int i = 0; i < rows; i++) {
String line = reader.nextLine();
data[i] = new String[line.length()];
for (int j = 0; j < line.length(); j++) {
data[i][j] = line.substring(j, j+1);
}
}
reader.close();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < data[i].length; j++) {
System.out.print(data[i][j]);
}
System.out.println();
}
}
This implementation can handle unknown number of lines and unknown length of each line.
If you wanna stick with your Array a possible solution would be
public static void main(String[] args) throws FileNotFoundException {
Scanner s = new Scanner(new File("D:/trabalho/maze.txt"));
String[][] list = new String[10][5];
for(int x = x; s.hasNextLine();x++ ){
for(int i = 0; i < 5 ; i++){
list[x][i] = s.nextLine();
}
}
s.close();
System.out.println(list);
}
So you don't even need a 2D array Here because the String Class acts like an char Array in C++.
Another solution would be to use ArrayLists
public static void main(String[] args) throws FileNotFoundException {
Scanner s = new Scanner(new File("D:/trabalho/maze.txt"));
ArrayList<String> list = new ArrayList<String>;
while (s.hasNextLine()){
list.add(s.nextLine());
}
s.close();
System.out.println(list);
}
So now you have a list that grows with your amount of Data and also you can just use add Method.
the line ArrayList<String> means that your arrayList just can store data from class String
Here you go!
public static void main(String[] str){
Scanner s = null;
try {
s = new Scanner(new File("path\\text.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
List<String> list = new ArrayList<String>();
while (s.hasNextLine()){
list.add(s.nextLine());
}
s.close();
Iterator<String> itr= list.listIterator();
while(itr.hasNext()){
System.out.println(itr.next().toString());
}
}
I am trying to read a txt file into a array of doubles. I am using the following code which reads every line of the file:
String fileName="myFile.txt";
try{
//Create object of FileReader
FileReader inputFile = new FileReader(fileName);
//Instantiate the BufferedReader Class
BufferedReader bufferReader = new BufferedReader(inputFile);
//Variable to hold the one line data
String line;
// Read file line by line and print on the console
while ((line = bufferReader.readLine()) != null) {
System.out.println(line);
}
//Close the buffer reader
bufferReader.close();
}catch(Exception e){
System.out.println("Error while reading file line by line:"
+ e.getMessage());
}
However I want to store the txt file into a 2d double array.
I ve tried the above to load also the dimension of the txt. But I am having problems with the exceptions catch (NoSuchElementException e), it seems that it couldnt read the file.
try {
while (input.hasNext()) {
count++;
if (count == 1) {
row = input.nextInt();
r = row;
System.out.println(row);
continue;
} else if (count == 2) {
col = input.nextInt();
System.out.println(col);
c = col;
continue;
} else {
output_matrix = new double[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
String el = input.next();
Double temp = Double.valueOf(el);
double number = temp.doubleValue();
//output_matrix[i][j] = el;
output_matrix[i][j] = number;
//System.out.print(output_matrix[i][j]+" ");
}
//System.out.println();
}
}
}
} catch (NoSuchElementException e) {
System.err.println("Sfalma kata ti tropopoisisi toy arxeioy");
System.err.println(e.getMessage()); //emfanisi tou minimatos sfalmatos
input.close();
System.exit(0);
} catch (IllegalStateException e) {
System.err.println("Sfalma kata ti anagnosi toy arxeioy");
System.exit(0);
}
You might want to be using the Scanner class for it, especially the Scanner.nextDouble() method.
Also, if you don't know in advance the dimensions of the array - I'd suggest using an ArrayList instead of a regular array.
Code example:
ArrayList<ArrayList<Double>> list = new ArrayList<>();
while ((line = bufferReader.readLine()) != null) {
ArrayList<Double> curr = new ArrayList<>();
Scanner sc = new Scanner(line);
while (sc.hasNextDouble()) {
curr.add(sc.nextDouble());
}
list.add(curr);
}
At firs declare a list and collect into it all read lines:
List<String> tempHistory = new ArrayList<>();
while ((line = bufferReader.readLine()) != null) {
tempHistory.add(line);
}
Then, after bufferReader.close(); convert this tempHistory list into double[][] array.
double[][] array = new double[tempHistory.size()][];
for (int i = 0; i < tempHistory.size(); i++) {
final String currentString = tempHistory.get(i);
final String[] split = currentString.split(" ");
array[i] = new double[split.length];
for (int j = 0; j < split.length; j++) {
array[i][j] = Double.parseDouble(split[j]);
}
}
It works, but as I added in comments, this is a not so good solution, and is better to use Collections instead of array.
BTW, it works even the rows lengths are different for different lines.
I previously asked a question about converting a CSV file to 2D array in java. I completely rewrote my code and it is almost reworking. The only problem I am having now is that it is printing backwards. In other words, the columns are printing where the rows should be and vice versa. Here is my code:
int [][] board = new int [25][25];
String line = null;
BufferedReader stream = null;
ArrayList <String> csvData = new ArrayList <String>();
stream = new BufferedReader(new FileReader(fileName));
while ((line = stream.readLine()) != null) {
String[] splitted = line.split(",");
ArrayList<String> dataLine = new ArrayList<String>(splitted.length);
for (String data : splitted)
dataLine.add(data);
csvData.addAll(dataLine);
}
int [] number = new int [csvData.size()];
for(int z = 0; z < csvData.size(); z++)
{
number[z] = Integer.parseInt(csvData.get(z));
}
for(int q = 0; q < number.length; q++)
{
System.out.println(number[q]);
}
for(int i = 0; i< number.length; i++)
{
System.out.println(number[i]);
}
for(int i=0; i<25;i++)
{
for(int j=0;j<25;j++)
{
board[i][j] = number[(j*25) + i];
}
}
Basically, the 2D array is supposed to have 25 rows and 25 columns. When reading the CSV file in, I saved it into a String ArrayList then I converted that into a single dimension int array. Any input would be appreciated. Thanks
so you want to read a CSV file in java , then you might wanna use OPEN CSV
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import au.com.bytecode.opencsv.CSVReader;
public class CsvFileReader {
public static void main(String[] args) {
try {
System.out.println("\n**** readLineByLineExample ****");
String csvFilename = "C:/Users/hussain.a/Desktop/sample.csv";
CSVReader csvReader = new CSVReader(new FileReader(csvFilename));
String[] col = null;
while ((col = csvReader.readNext()) != null)
{
System.out.println(col[0] );
//System.out.println(col[0]);
}
csvReader.close();
}
catch(ArrayIndexOutOfBoundsException ae)
{
System.out.println(ae+" : error here");
}catch (FileNotFoundException e)
{
System.out.println("asd");
e.printStackTrace();
} catch (IOException e) {
System.out.println("");
e.printStackTrace();
}
}
}
and you can get the related jar file from here