I am filtering a file rows with an if condition and I need to make a new array which containing only the values that satisfy the condition.
I can get them in the console but I don't know how to assign them to a table, can anyone help me please?
String section_title;
for (int j=11; j<row_num; j++)
{
Row row = (Row) rowIterator.next();
Cell s0 = sheet.getRow(j-1).getCell(0);
if(s0.toString()!="" )
{
section_title = s0.toString();
d = j-1;
System.out.println(d);
}
}
Consider using an arraylist object to hold those values.
It would look something like this:
String section_title;
ArrayList<int> list = new ArrayList<int>(); // instanciate the array list
for (int j=11; j<row_num; j++)
{
Row row = (Row) rowIterator.next();
Cell s0 = sheet.getRow(j-1).getCell(0);
if(s0.toString()!="" )
{
section_title = s0.toString();
d = j-1;
list.add(d); // Add d to the list
}
}
System.out.println(list); // Print the final list
The goal is to scan some input and to get an array of int as a result.
As we do not know the final number of entries for the array, we should use something with a variable length for that purpose. Usually, this would be a List of some kind, but List is not defined for int (or other primitives), only for object types like Integer. So we would need a transformation step after collecting the numbers.
Since Java 8, we have Streams, and with that, the problem can be solved more directly:
String section_title;
var builder = IntStream.builder();
for( var j = 11; j < row_num; ++j )
{
var row = (Row) rowIterator.next();
Cell s0 = sheet.getRow( j - 1 ).getCell( 0 );
if( !s0.toString().isEmpty() )
{
section_title = s0.toString();
builder.add( Integer.valueOf( j - 1 ) );
}
}
var array = builder.build().toArray();
System.out.println( array );
Under the hood, this solution may end up to be nearly the same as one using Collections. But it still looks neater.
Related
I want to have each index of the 2D array to have a unique value for each iteration but my problem is that whenever the user inputs the first value for the first index, it automatically overwrites the remaining empty indexes into the first index value...
String[][] ProductAllData1 = new String[10][6]; // an array that may store 10 unique elements(each element has 6 values)
String[] receivedPInputs = getPInputs(); // gets the values from a function that asks the user to input values
for (int d = 0; d < ProductAllData1.length; d++){
ProductAllData1[d] = receivedPInputs;
System.out.print(Arrays.toString(ProductAllData1[d]));
System.out.println("");
}
Am I missing something to add or is my for loop not correct?
Your responses would be highly appreciated!!
You are assigning the same value to all the indices.
Put the getPInputs() inside the loop!
String[][] ProductAllData1 = new String[10][6];
String[] receivedPInputs;
for (int d = 0; d < ProductAllData1.length; d++) {
receivedPInputs = getPInputs();
ProductAllData1[d] = receivedPInputs;
System.out.print(Arrays.toString(ProductAllData1[d]));
System.out.println("");
}
I'm currently trying to figure out how to add values into a full 2d array. Any help would be appreciated.
This is what i currently have.
public static ObjectA[][] addValue(ObjectA value, ObjectA[][] oldArray)
{
//Creates a new array with an extra row
ObjectA[][] newArray = new ObjectA[oldArray.length +1][oldArray[0].length]
for (int i= 0 ; i < newArray.length; i++)
{
for (int ii = 0; ii <= newArray[0].length; ii++)
{
// when the index exceeds the oldArray
// it will add the value to the newArray
if (i <= oldArray.length)
{
newArray[i][ii] = oldArray[i][ii];//copies all values into newArray
}
else
{
newArray[i][ii] = value; //adds value to the last row
}
}
}
return newArray;
}
What I currently have done is input a value to the new row however the method is going to be called multiple times to add more than one value. Which mean it's going to create multiple rows rather than adding to the next available column.
EDIT:
mistyped the data type the array and value are suppoed to be objects.
First, your code throws an IndexOutOfBoundsException. Here is why:
Consider the if (i <= oldArray.length) clause. Say, oldArray.length is 3. When i = 3, newArray[i][ii] = oldArray[i][ii] line seeks the oldArray[3][ii] elements but there are no such elements. All the possible elements of oldArray is oldArray[0][ii], oldArray[1][ii] and oldArray[2][ii], since counting starts with 0 in programming.
Second, I didn't get the point of adding another row for each next value. If you're not going to add a set of values to each row, then, why do you consider expanding number of rows?
This is a typical situation when you need to make a tradeoff between element access complexity and complexity of adding new column
If you need fast column adding without new structure allocation you should use LinkedList as a storage of rows and call list.add(row) every time you need to add a new column so your code will look like:
public static void addValue(int value, LinkedList<int[]> list) {
int[] row_you_need_to_add = new int[list.get(0).length];
for (int i = 0; i < list.get(0).length; i++) {
row_you_need_to_add[i] = value;
}
list.add(row_you_need_to_add);
}
As 2D Array is an Array which consist of an array within an Array. So at every index of 2D array there is another array is present and has a specific size.
public static ObjectA[][] addValue(ObjectA value, ObjectA[][] oldArray) {
ObjectA[][] newArray = new ObjectA[oldArray.length +1][oldArray[0].length]
for (int i= 0 ; i < newArray.length; i++) {
for (int ii = 0; ii <= newArray[0].length; ii++) {
// when the index exceeds the oldArray
// it will add the value to the newArray
if (i <= oldArray.length) {
newArray[i][ii] = oldArray[i][ii];//copies all values into newArray
} else {
newArray[i][ii] = value; //adds value to the last row
}
}
}
return newArray;
}
I'm new to Java, and I'm certain I'm not using lists properly, but I'm saving loads of user input responses as elements of a String list (as a side question, do I want a String list or an array list for this task?), and I later want to print out these elements at the end of the program. However, I want to do this automatically through a for loop, but I don't know the length of the list to make the for loop do its job. I tried
for(int j = 0; j <= (results.length-1); j++){
where "results" is the name of the String list, but it's giving me the error "cannot find symbol." Is there any way to get the length of a String list in Java? And am I using the list thing properly, or should I be trying an array list instead? Any help would be greatly appreciated.
If, by length, you mean the total number of elements contained in your list, you can use the size() method. It returns an integer that specifies the number of elements present in the list.
As for your for loop, you can do this:
for (int j = 0; j < results.size(); j++) {
//write loop logic here
}
List<String> results = new ArrayList<>();
// add list elements using results.add("");
for( final String result : results )
{
// process the results
System.out.println( "Result: " + result );
}
Alternatively
//length of array list
int listLength = results.size();
for( int i = 0; i < listLength; i++ )
{
System.out.println( "Result: " + results.get( i ) );
}
// print result 31
System.out.println("i hope you can have a nice day.".length());
List<String> list = new ArrayList<String>();
list.add("i hope you can have");
list.add(" a nice day");
list.add(".");
// [i hope you can have, a nice day, .]
System.out.println(list.toString());
System.out.println(list.toString().length()-(list.size()-1)*2-2);
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.
this code is just a test to find duplicates of a vector and remove them ,while removing the correspoding objects of 2 other vectors
This gives as output an Arrayoutofindex in line 3.Do you have any suggestions?
for (int k = 0 ; k < vA.size() ; k++)
{
Object a = vA.elementAt(0);
Object b = vA.elementAt(k);
if(a == b && k!=0)
{
int duplicate = vA.indexOf(b);
vA.removeElementAt(duplicate);
vB.removeElementAt(duplicate);
vC.removeElementAt(duplicate);
}
According to This question, Which i advice you to read, as it explains the bets ways to remove duplicates from an array,
You can use the following methods :
The removeDuplicate Method:
/** List order not maintained **/
public static void removeDuplicate(ArrayList arlList)
{
HashSet h = new HashSet(arlList);
arlList.clear();
arlList.addAll(h);
}
And The removeDuplicateWithOrder Method:
/** List order maintained **/
public static void removeDuplicateWithOrder(ArrayList arlList)
{
Set set = new HashSet();
List newList = new ArrayList();
for (Iterator iter = arlList.iterator(); iter.hasNext();) {
Object element = iter.next();
if (set.add(element))
newList.add(element);
}
arlList.clear();
arlList.addAll(newList);
}
Hopes theese help you somehow.
You are doing vA.size() in for condition, and then trying to remove elements from vA inside loop. This is causing the exception.
Store vA.size in a seperate variable
int size = vA.size();
for (int k = 0 ; k <= size ; k++)
Then, inside loop, where ever you have
vA.removeElementAt(duplicate);
instead, store this is seperate new list.
toBeRemoved.add(b);//b is the element to be removed later
and remove all the toBeRemoved from vA after loop.
vA.removeAll(toBeRemoved );
EDITED:
Your new code will look like this-
int vASize = vA.size();
List vAToBeRemoved = new ArrayList();
for (int k = 0 ; k < vASize; k++)
{
Object a = vA.elementAt(0);
Object b = vA.elementAt(k);
if(a == b )
{
int duplicate = vA.indexOf(b);
vAToBeRemoved.add(b);//elements to be removed later.
vA.removeElementAt(duplicate);
vB.removeElementAt(duplicate);
vC.removeElementAt(duplicate);
}
}
vA.removeAll(vAToBeRemoved);
for (int k = 0 ; k <= vA.size() ; k++)
k should run only from 0 to va.size() - 1 because it is zero-based, i.e. the first index is 0. Rewrite the loop statement as:
for (int k = 0 ; k < vA.size() ; k++)
Use below method to remove dulplicate elements from vector
public static Vector removeDuplicateResults(Vector resultsVector) {
for(int i=0;i<resultsVector.size();i++){
for(int j=0;j<resultsVector.size();j++){
if(i!=j){
Object resultsVectorObject1 = resultsVector.elementAt(i);
Object resultsVectorObject2 = resultsVector.elementAt(j);
Object[] resultsObjectArray1 = (Object[]) resultsVectorObject1;
Object[] resultsObjectArray2 = (Object[]) resultsVectorObject2;
if(Arrays.equals(resultsObjectArray1, resultsObjectArray2))
{
resultsVector.removeElementAt(j);
}
}
}
}
return resultsVector;
}