I've got something like this:
List<int[]> myList= new ArrayList<int[]>();
int tmp[] = new int[size];
for(int i = 0; i<anotherList.size(); i++) {
for (int j = 0; j<size; j++) {
tmp[j] = anotherList.get(i)[j];
}
myList.add(tmp);
}
When I want to print myList, I see only last added tmp. Why?
for(int i = 0 ; i<myList.size(); i++){
for(int j=0; j<myList.get(i).length; j++){
System.out.print(myList.get(i)[j]+ " ");
}
System.out.println();
}
Your code only ever creates one array named "tmp". You need to move the declaration of tmp inside the first for loop, instead of having it before the for loop.
The tmp array is constructed outside the loops, and thus the same instance is being added to myList. To fix, add a different instance to the List at every iteration (eg create the array inside the first for loop)
Related
So in java, This is what I'm trying to execute:
num [0]=list.get(2);
num [1]=list.get(4);
num [2]=list.get(6);
num [3]=list.get(8);
I have an arraylist of integers called list and I want to put the values that are in the even number indices starting at 2 into an array of integers called num in the indices 0,1,2,3,etc. My problem is, I'm trying to do this within a for loop but I'm not sure how to go about it. Here is what I have:
for (int i=0; i<list.size()-2; i++){
num[i] = list.get(i+2);
}
My problem here is, after incrementing i, my arraylist goes to the next index also instead of every other index. I've tried multiple variations of this loop but I keep coming to the same problem.
This should do it:
int max = list.size()/2;
if(list.size()%2==0) max-=1; // prevents IndexOutOfBounds for even list lengths
for (int i=0; i<max; i++){
num[i] = list.get(i*2 + 2);
}
You can try something like this.
for (int i=0,j=0; i<list.size()-2; i+=2,j++){
num[j] = list.get(i+2);
}
The loop should continue as long as the i is less then (list.size()-1)/2
List<Integer> list = Arrays.asList(0,1,2,3,4,5,6);
int size = (list.size()-1)/2;
int[] num = new int[size];
for (int i=0; i<size; i++){
num[i] = list.get(i*2+2);
}
System.out.println("num="+ Arrays.toString(num));
Here is DEMO
This should work:
for(int i = 0; i < list.size() - 2; i++)
num[i] = list.get((i * 2) + 2);
Why is this ArrayList empty when I print it out?
ArrayList<InterviewQuestion> interviewQuestionArrayList = new ArrayList<>();
for (int i = 0; i <interviewQuestionArrayList.size(); i++) {
interviewQuestionArrayList.add(new InterviewQuestion());
}
System.out.println(interviewQuestionArrayList);
You have created arraylist but before adding you are trying to looping through it.. size will be zero initially..
If you know how many interviewQuestions are there then you can loop with that number.
ex:
for (int i = 0; i <numberOfQuestions; i++) {
interviewQuestionArrayList.add(new InterviewQuestion());
}
numberOfQuestions should be predifined..
Initially if you dont know how many times you want to add then you can use while loop. But you should exit from while based on some condition
like,
boolean flag = true;
while(flag) {
interviewQuestionArrayList.add(new InterviewQuestion());
if(condition) flag = false;
} //something like this
As far as i can see, your List is empty when you enter the loop.
Thus its size() will return 0 and the loop will not add any elements.
your code basically does
for (int i = 0; i < 0; i++) {
interviewQuestionArrayList.add(new InterviewQuestion());
}
Here you create an empty list -> this means the size is currently 0
ArrayList<InterviewQuestion> interviewQuestionArrayList = new ArrayList<>();
The following loop is never executed because i (now 0) is never < size (now 0)
This means there are no Objects added to your list
for (int i = 0; i <interviewQuestionArrayList.size(); i++) {
interviewQuestionArrayList.add(new InterviewQuestion());
}
Try using i<10 as the condition in the for loop to add 10 elements to the list
if this 2 staments are followed by each other, then your list is never populated:
ArrayList<InterviewQuestion> interviewQuestionArrayList = new ArrayList<>();
for (int i = 0; i <interviewQuestionArrayList.size(); i++) {
interviewQuestionArrayList.add(new InterviewQuestion());
}
ergo, you have an empty list to print
System.out.println(interviewQuestionArrayList);
you can play with some dummyData that you add when declaring the list
I'm trying to practice using Arrays methods in java. I used the following code to make an Java array:
int numArr[] = new int[10];
for(int i = 0; i< numArr.length;++i)
{
numArr[(numArr.length)-i-1] = (i+1)*2;
System.out.println("numArr[i]" + numArr[i]);
}
My intention was to use this to make the list 20,18,...,4,2. Then, I wanted to use the Arrays sort method to see if it worked properly.
The odd result that I can't understand is that above code prints:
numArr[i] = 0;
numArr[i] = 0;
numArr[i] = 0;
numArr[i] = 0;
numArr[i] = 0;
numArr[i] = 10;
numArr[i] = 8;
numArr[i] = 6;
numArr[i] = 4;
numArr[i] = 2;
I understand the simple mistake with printing the i each time but I don't understand why the initial results are all the 0. I thought maybe it just failed and they were still just initialized to the 0 default. But then I realized that after later in the code after using Arrays.sort(), the list prints correctly for all of the indexes 2,4,...,18,20.
What mistake am I making on the pre-sorted array print?
Your mistake is in how you are indexing into the array in the loop. You are assigning to array element (numArr.length)-i-1 but printing array element i. Try printing array element (numArr.length)-i-1 inside the loop to see the value you just assigned.
Let's say i=0, or the first loop.
numArr[(numArr.length)-i-1] = (i+1)*2;
Run that through, you get
numArr[9] = 2;
Yet, you print numArr[0], which is not yet assigned.
You'll start seeing values once you reach the midpoint of the array
If you are still confused, write out your algorithm on paper
You are trying to print the results even before they are populated in the array.
Here you are populating from behind but trying to print from front(Which are not yet given any value)
Wait for the array to get populated and loop through the array to get the proper result
Doing this should solve your problem,
for(int i = 0; i< numArr.length;++i)
{
numArr[(numArr.length)-i-1] = (i+1)*2;
}
for(int i = numArr.length-1; i>-1;i--)
{
System.out.println(numArr[i]);
}
You are trying to print indexes which has their default value (0) in it. Instead, try printing the indexes which you've already assigned a value into
for(int i = 0; i< numArr.length;++i)
{
numArr[i] = (i+1)*2;
System.out.println("numArr[i]" + numArr[i]);
}
or
for(int i = 0; i< numArr.length;++i)
{
numArr[(numArr.length)-i-1] = (i+1)*2;
System.out.println("numArr[i]" + numArr[(numArr.length)-i-1]);
}
As #Vinay pointed out when printing you are using i as subscript for array elements that didn't get populated yet. If you want to print array while populated you have to use the same index
int numArr[] = new int[10];
for(int i = 0; i< numArr.length;++i)
{
numArr[(numArr.length)-i-1] = (i+1)*2;
System.out.println("numArr[(numArr.length)-i-1]);
}
The easiest way is populate the array and then print the result with another loop:
Test:
public class Test
{
public static void main ( String [ ] args )
{
int numArr[] = new int[10];
for(int i = 0; i< numArr.length;++i)
{
numArr[(numArr.length)-i-1] = (i+1)*2;
}
for(int i = 0; i < numArr.length; i++)
{
System.out.println("numArr["+i+"]" + numArr[i]);
}
}
}
Output:
numArr[0]20
numArr[1]18
numArr[2]16
numArr[3]14
numArr[4]12
numArr[5]10
numArr[6]8
numArr[7]6
numArr[8]4
numArr[9]2
int numArr[] = new int[10];
for(int i = numArr.length-1; i >= 0; i--)
{
numArr[i] = (i+1)*2;
System.out.println("numArr["+i+"]" + numArr[i]);
}
Output:
numArr[9]20
numArr[8]18
numArr[7]16
numArr[6]14
numArr[5]12
numArr[4]10
numArr[3]8
numArr[2]6
numArr[1]4
numArr[0]2
Is this what you wanted to look like?
[Vote up if helped]
So, I have a method like this
public String[][] getArgs(){
And, I want it to get results out of a for loop:
for(int i = 0; i < length; i++){
But how do I append them to the array instead of just returning them?
Create a String[][] array inside your method, fill this array inside a loop (or in any other way) and return that array in the end.
If you are sure you want to have only one for loop (instead of two, typical for 2-dimensional array), ensure your loop will go through the number of examples equal to the number of fields in your String[][] array. Then you can calculate the double-dimension array indexes from your single loop-iterator, for example:
for(int i = 0; i < length; i++){
int a = i % numberOfCollumnsInOutput;
int b = i / numberOfCollumnsInOutput;
String[a][b] = sourceForYourData[i];
}
(Of course which array dimension you treat as collumns (and which to be rows) depends on yourself only.) However, it is much more typical to go through an n-dimensional array using n nested loops, like this (example for 2d array, like the one you want to output):
for(int i = 0; i < dimensionOne; i++){
for(int j = 0; j < dimensionTwo; j++){
array[i][j] = someData;
}
}
For your interest. A sample code according to Byakuya.
public String[][] getArgs(){
int row = 3;
int column =4;
String [][] args = new String[row][column];
for(int i=0;i<row;i++)
for(int j=0;j<column;j++)
args[i][j] = "*";
return args;
}
You can make a LinkedList from that array, and then append the elements to it, and then create a new array from it. If you are not sure i'll post some code.
I am using this code to insert the details in to TwoDimensional Array. But while retrieving the data from the array the first element value changes to null.
Cursor consultancy = db.getConsultancy(this);
if(consultancy!=null)
{
consultancy.moveToFirst();
consultancy.moveToNext();
consultancynames = new String[(int) db.getConsultancyCount()-1];
for(int i=0;i<db.getConsultancyCount()-1;i++)
{
consultancynames[i] = consultancy.getString(2);
int consultantid = Integer.parseInt(consultancy.getString(consultancy.getColumnIndex(TimeAndExpensesLocalDB.CT_CONSULTANCYID)));
Cursor project_namecur = db.getProjectCode(this, consultantid);
if(project_namecur!=null)
{
project_namecur.moveToFirst();
projectname = new String[(int) db.getConsultancyCount()][project_namecur.getCount()];
for(int j=0;j<project_namecur.getCount();j++)
{
projectname[i][j] = project_namecur.getString(3);
project_namecur.moveToNext();
}
}
consultancy.moveToNext();
}
}
//... Print array
for (int i =0; i < consultancynames.length; i++) {
for (int j = 0; j < projectname.length; j++) {
System.out.print(" " + projectname[i][j]);
}
System.out.println("");
}
Output
05-25 12:58:22.700: I/System.out(2373): null null null
05-25 12:58:22.700: I/System.out(2373): Other-1 Other-2 Other-3
I am not sure what is happening.
Thanks for your help guys..
You're creating a new array on each iteration of the loop:
projectname = new String[(int) db.getConsultancyCount()][project_namecur.getCount()];
So on the first iteration you're creating an array and filling in the first "row" of the array. On the second iteration you're creating a new array (which will default to having null elements) and filling in the second row.
I suspect you need to allocate the "outer" array once before the loop, then allocate the "inner" array based on how many project names there are for that consultant:
// Note: more idiomatic names would be consultancyNames and
// projectNames. It's also unclear why you're subtracting one from the count...
consultancynames = new String[(int) db.getConsultancyCount() - 1];
projectnames = new String[consultancynames.length][];
for (int i = 0;i< consultancenames.length; i++) {
...
projectnames[i] = new String[project_namecur.getCount())];
...
}
Then you'll need to change your display code too, e.g. to
for (int i =0; i < projectname.length; i++) {
for (int j = 0; j < projectname[i].length; j++) {
System.out.print(" " + projectname[i][j]);
}
System.out.println("");
}
Note that you can't do the following:
projectname = new String[(int) db.getConsultancyCount()][project_namecur.getCount()];
for(int j=0;j<project_namecur.getCount();j++)
{
projectname[i][j] = project_namecur.getString(3);
project_namecur.moveToNext();
}
Here's why:
After the first line projectname will be an array of arrays.
Since the arrays are object references you have an array of object references.
Since the default value of an object reference is null, you'll have an array of null elements.
This means you can't do
projectname[i][j] = project_namecur.getString(3);
since it corresponds to
String[] row = projectname[i];
// row == null !
row[j] = project_namecur.getString(3);