I have a file that contains a square table of floats. The file is an example, therefore the number of rows and columns may change in the other files for reading.
I am getting an out-of-bounds exception and can't figure out what the problem is.
while ((line=bufferedReader.readLine())!=null){
String[] allIds = line.split(tabSplit);
String[] allFloats = new String[allIds.length-2];
//i do "length-2" because the first two columns in the table are not numbers and are
supposed to be ignored.
System.arraycopy(allIds, 2, allFloats, 0, allIds.length-2);
int rows = rowsNumber;
int cols = colsNumber;
//i have "rows" and "cols" values already extracted from the file and they return the
correct integers.
double [][]twoD = new double[rows][cols];
int rowCount = 0;
for (int i = 0; i<rows; i++) {
twoD[rowCount][i] = Double.parseDouble(allFloats[i]);
}
rowCount++;
}
}
The table i have looks something like this, but with more rows and columns:
#18204 name01 2.67 2.79 2.87 2.7
#12480 name02 4.01 3.64 4.06 4.24
#21408 name03 3.4 3.55 3.34 3.58
#a2u47 name04 7.4 7.52 7.62 7.23
#38590 name05 7.63 7.29 8 7.72
When I print allFloats, it returns each row in a separate array correctly. I don't understand why I get an error when I try to create a 2D array.
Edit:
Try the following:
int rowCount = 0;
int rows = rowsNumber;
int cols = colsNumber;
double[][] twoD = new double[rows][cols];
while ( ( line=bufferedReader.readLine() ) != null )
{
String[] allIds = line.split( tabSplit );
String[] allFloats = new String[allIds.length-2];
System.arraycopy(allIds, 2, allFloats, 0, allIds.length-2);
for (int i = 0; i<cols; i++)
{
twoD[rowCount][i] = Double.parseDouble(allFloats[i]);
}
rowCount++
}
You are creating the two dimensional double array in every line. I would recommend first generating a two dimensional array holding all the float values for each line the after that iterate back over that array and then parse a double from that.
Related
Currently I have a String called x that displays the following
100
000
000
How do I convert it into an nxn, int[][] array called board? The array contents should look like how its printed above. However, the array must be initialized depending on the rows / columns of the String. In the example above, it should be a 3x3 array.
I'm not sure how to start. The first problem I have is iterating through the String and counting how many "rows" / "columns" are in the String,
In addition to writing the contents in the correct order. Here is what I have attempted so far...
for (int i = 0; i < x.length(); i++)
{
char c = x.charAt(i);
board[i][] = c;
}
I assume that your string stored in Java looks like String str = "100\r\n000\r\n000";, then you can convert it to a 2D array as follows:
Code snippet
String str = "100\r\n000\r\n000";
System.out.println(str);
String[] str1dArray = str.split("\r\n");
String[][] str2dArray = new String[str1dArray.length][str1dArray[0].length()];
for (int i = 0; i < str1dArray.length; i++) {
str2dArray[i] = str1dArray[i].split("");
System.out.println(Arrays.toString(str2dArray[i]));
}
Console output
100
000
000
[1, 0, 0]
[0, 0, 0]
[0, 0, 0]
Updated
Following code snippet shows how to convert the string to a 2D integer array with Lambda expression (since Java 8).
int[][] str2dArray = new int[str1dArray.length][str1dArray[0].length()];
for (int i = 0; i < str1dArray.length; i++) {
str2dArray[i] = Arrays.stream(str1dArray[i].split("")).mapToInt(Integer::parseInt).toArray();
// This also works without using Lambda expression
/*
for (int j = 0; j < str1dArray[i].length(); j++) {
str2dArray[i][j] = Integer.parseInt(String.valueOf(str1dArray[i].charAt(j)));
}
*/
System.out.println(Arrays.toString(str2dArray[i]));
}
With your data you will have only the first row, you need more data.
String a = "100\n" +
"000\n" +
"000";
String matriz[][] = {a.split("\n")};
So I want to add the rows and columns in this 2D array right here.
The array looks like this:
int[][] array = new int[3][3];
array[0][0] = 0;
array[1][0] = 0;
array[2][0] = 0;
array[1][0] = 0;
array[1][1] = 1;
array[1][2] = 2;
array[2][0] = 0;
array[2][1] = 2;
array[2][2] = 4;
So I have this set up in a 3x3 matrix on a sheet of paper and the first row should print out 0, second row should print out 3, third row should print out 6
first column should print out 0, second column should print out 3, third column should print out 6.
I have no clue where to start and I just need to see how to do this problem, because I have a few questions after this that involve this, so if you can just give me code that I can read it would be really helpful! Thanks!
The simplest way is to create two for loops - outer one goes through the rows, inner one goes through the columns. Then sum up the values for every column of a given row.
int[] colSums = {0,0,0};
for (int c=0;c<array.length;c++) {
int rowSum = 0;
for (int c2=0;c2<array[c].length;c2++) {
rowSum += array[c][c2];
colSums[c2] += array[c][c2];
}
System.out.println("Sum of row "+c+": "+rowSum);
}
for (int c=0;c<colSums.length;c++) {
System.out.println("Sum of column "+c+": "+colSums[c]);
}
I have a CSV file which I have to read to a 2D string array (it must be a 2D array)
However it has different column number, like:
One, two, three, four, five
1,2,3,4
So I want to read those into an array. I split it everything is good, however I don't know how not to fill the missing columns with NULLs.
The previous example is:
0: one,two,three,four,five (length 5)
1: 1,2,3,4,null (length 5)
However I want the next row's length to be 4 and not 5 without null.
Is this possible?
This is where I've got so far (I know it's bad):
public static void read(Scanner sc) {
ArrayList<String> temp = new ArrayList<>();
while(sc.hasNextLine()) {
temp.add(sc.nextLine().replace(" ", ""));
}
String[] row = temp.get(0).split(",");
data = new String[temp.size()][row.length];
for (int i = 0; i < temp.size(); ++i) {
String[] t = temp.get(i).split(",");
for (int j = 0; j < t.length; ++j) {
data[i][j] = t[j];
}
}
}
Sounds like you want a non-rectangular 2-dimensional array. You'll want to avoid defining the second dimension on your 2D array. Here's an example:
final Path path = FileSystems.getDefault().getPath("src/main/resources/csvfile");
final List<String> lines = Files.readAllLines(path);
final String[][] arrays = new String[lines.size()][];
for (int i = 0; i < lines.size(); i++) {
arrays[i] = lines.get(i).split(",");
}
All lines are read into a List so that we know the first dimension of the 2D array. The second dimension for each row is determined by the result of the split operation.
Just to keep my skills sharp, I decided to write a small programme that prints out the values of an array, after being given two variables that each contain a different value.
My expectation was that each value would show onscreen, but this did not happen. Instead, only the last element's value was displayed onscreen (in the code below, being the number "2" --> That is an integer, not a string).
Why is this?
Also, why does dynamic initialisation produce the result I wish, but not the way I do it in the code?
Many thanks.
int[] arrayOne;
arrayOne = new int[2];
int numOne = 1;`
int numTwo = 2;`
for (int i = 0; i < arrayOne.length; i++) {`
arrayOne[i] = numOne;
arrayOne[i] = numTwo;
System.out.println(arrayOne[i]);
}
If you want to put the values of two variables into an array, you need to use two assignments:
arrayOne[0] = numOne;
arrayTwo[1] = numTwo;
Now you can use a for loop to print out the contents of the array.
This kind of defeats the purpose of using an array, though.
You're setting different values to same location, causing only last value to be saved.
Your code similar to doing:
arrayOne[0] = 1;
arrayOne[0] = 2;
After these two lines, arrayOne[0] will hold the value of 2.
If you want to put these two values, you need to put them in different places:
arrayOne[0] = 1;
arrayOne[1] = 2;
In Java (and in almost any language I know), an array can only contain one vale per cell i.e. if you do "array[i] = 1" and after "array[i] = 2" , then the i-cell will CHANGE its value from 1 to 2, not append the value 2 after the 1. In the end, youre array will contain numTwo in every single cell.
If you want to initialize the array with a different value in each cell, I'm afraid you need to do it manually, not using the loop.
You need to do the population of your array before you iterate through it with the loop.
arrayOne[0] = numOne;
arrayOne[1] = numTwo;
Then do your loop:
for (int i = 0; i < arrayOne.length; i++)
{
System.out.println(arrayOne[i]);
}
Many ways to initialize an array...
int[] a = new int[2];
a[0] = 1;
a[1] = 2;
Or:
int[] a = new int[2];
for( int i = 0; i < a.length; i++ ){
a[i] = i + 1;
}
Or:
int[] a = new int[]{ 1, 2 };
Or.
int valOne = 1;
int valTwo = 2;
int[] a = new int[]{ valOne, valTwo };
Take care when you see more than one assignment to the same array element in a loop as you have it before the println. Is this what you want? The second one wins and sets the current (i-th) element to 2.
You need to do something like this:
public class demo{
private static int i = 0;
private static int[] demo = new int[10];
public static void main(String[] args){
for(int i = 0; i < 10; i++){
addElementToArray(i);
}
for(int i = 0; i < demo.length; i++){
System.out.println(demo[i]);
}
addElementToArray(i);
}
public static void addElementToArray(int input){
try{
demo[i] = input;
i++;
}catch(ArrayIndexOutOfBoundsException e){
e.printStackTrace();
}
}
}
Don't set the values inside the for-loop either, that is (imo) plain stupid, for what you are trying to achieve
Assume that I already have a 2D int value[i][j]. This works well and I can store a single int in each index. Now I want to add a second array int data[i][j] so I can store multiple int data in it. Am I approaching it correctly?
For example in a Sudoku situation:
value[0][0] = 0
But in an other grid I have all possible values in each index
data[0][0] = {1,2,3,4,5,6,7,8,9}
Is it possible to do that? If so what should I do with my data? I'm really confused about arrays, multi-dimensional arrays, ArrayLists, etc. I'm unsure which to use.
For example:
Values {1,2,3},{4,5,6},{7,8,9}
In an 3x3:
1,2,3
4,5,6
7,8,9
Data{1,2,3,4,5,6,7,8,9}
Which I want to store it now in each grid and will have a method to remove from that list in later steps because I'm cancelling those possibilities in that grid. And the data in data{} doesn't have to be shown to the user.
I hope this will clear to some extent
Internally, Java stores 2 dimensional arrays as an array of arrays:
Suppose you have
int [][] nums = new int[5][4];
The above is really equivalent to a 3-step process:
int [][] nums;
// create the array of references
nums = new int[5][];
// this create the second level of arrays
for (int i=0; i < nums.length ; i++)
nums[i] = new int[4]; // create arrays of integers
Simply use boolean[] for possible choices. You could use Set (http://docs.oracle.com/javase/7/docs/api/java/util/Set.html), but for a small pool of fixed size with boolean options only, Set is an overkill (mainly due to code overhead).
Next thing is, that the basic principle of OOP (and Java is, or at least should be OOP) is that you should group data into objects/classes based on their functionality. If you're trying to aggregate a cell in a grid, you should create a grid (2D array) of objects, not a couple of int or boolean (or whatever) arrays.
First create a class, e.g.
class Cell {
final int POSSIBILITES = 9;
int actual_value;
boolean[] possible_values = new boolean[POSSIBILITES]; // for each number
Cell( int actual_value ) {
this.actual_value = actual_value;
for( int i = 0; i < POSSIBILITES; i++ )
possible_values[i] = true;
}
}
and then initialize/instantiate an array of objects
//...
final int X_SIZE = 9, Y_SIZE = 9;
Cell[][] cells = new Cell[X_SIZE][Y_SIZE];
for( int i = 0; i < X_SIZE; i++ )
for( int j = 0; j < Y_SIZE; j++ )
cells[i][j] = new Cell( somevalue );
//...
And then access them by, for example
//note: it's more proper to use getter/setter pattern, so this is only a crude example
if ( cells[3][6].actual_value = 7 )
do_something();
cells[1][2].possible_values[0] = false; // we're numbering from 0 to 8, so value 1=> index 0, 2=>1... 9=>8
cells[1][2].possible_values[4] = true;
Yes, it is possible. For that I'd recommend a boolean[][][] where, for example, theArray[6][3][8] is a boolean indicating whether the number 8 is included in the cell at row 6, column 3.