Array is not setting values properly - java

The first 4 values are set properly in the new array. It has to do with something with my variable 'count' which is not being set properly. The goal of the program is to simply grab the even numbers, and put them in a new array.
I have added 4 to count as a test, and that seems to work perfectly but I dont think that is the issue here.
int[] list = {8,5,4,11,12,2,1,3,10,6,7};
int count = 0;
int gr = 0;
for(int n=0; n<list.length; n++)
{
if(list[n] % 2 == 0)
{
count++;
}
}
int[] evn = new int[count];
for(int k = 0; k<=count; k++)
{
if(list[k] % 2 == 0)
evn[gr++] = list[k];
}
return evn;
Currently, the array prints "8,4,12,2,0,0" when it should print "8,4,12,2,10,6"

This happens because count is always less than the size of the array(list.length), so in the second for-loop you are never iterating till the end of the array.
Change your second for-loop to iterate till the end of the array as shown below :
for(int k = 0; k < list.length; k++)

You're only traversing part of list, as stated in the for condition:
for(int k = 0; k<=count; k++)
^--here--^
This is because count has a lower value than the length of the original array. Change this condition to traverse the whole array:
for(int k = 0; k<list.length; k++)

To traverse the whole list change the following:
for(int k = 0; k<=count; k++)
To
for(int k = 0; k<list.length; k++)

Related

How to loop this statement with 3 changing values to setText for 40 textfields?

Here is the code when I haven't stored in a list. This gets what I want to display in different textfields but I want it to be shorter so I want to loop it.
//"answerStoration.retrieveDataChoices(i,TB)" is a function from other class that returns an arraylist;
quizAnswer1store.setText(answerStoration.retrieveDataChoices(1,TB).get(0));
quizAnswer2store.setText(answerStoration.retrieveDataChoices(1,TB).get(1));
quizAnswer3store.setText(answerStoration.retrieveDataChoices(1,TB).get(2));
quizAnswer4store.setText(answerStoration.retrieveDataChoices(1,TB).get(3));
quizAnswer1store2.setText(answerStoration.retrieveDataChoices(2,TB).get(0));
quizAnswer2store2.setText(answerStoration.retrieveDataChoices(2,TB).get(1));
quizAnswer3store2.setText(answerStoration.retrieveDataChoices(2,TB).get(2));
quizAnswer4store2.setText(answerStoration.retrieveDataChoices(2,TB).get(3));
quizAnswer1store3.setText(answerStoration.retrieveDataChoices(3,TB).get(0));
quizAnswer2store3.setText(answerStoration.retrieveDataChoices(3,TB).get(1));
quizAnswer3store3.setText(answerStoration.retrieveDataChoices(3,TB).get(2));
quizAnswer4store3.setText(answerStoration.retrieveDataChoices(3,TB).get(3));
I stored it in a List "quizAnswerSTORE" and I tried to loop but doesnt work.
int k = 0;
for(int i = 0; i<quizAnswerSTORE.size(); i++){
for(int j = 1; j < 11; j++){
while(k<4){
quizAnswerSTORE.get(i).setText(answerStoration.retrieveDataChoices(j,TB).get(k));
}
}
}
The expected result is to diplay different values from a database in different 40 txtfields. Because each time the loop values increments, it rolls through my database with different values. J variable represents the id in my database. And the K is an index in the values taken in the arrayList returned by retrieveDataAnswers function from a four columned database.
There you go. I hope you can solve this.
You can use mod to control maximun int values, for example i % 10 can't take values more than 10.
Example:
public class Main {
public static void main(String[] args) {
int j = 1;
int k = 0;
for(int i = 0; i < 40; i++) {
System.out.println("quizAnswerSTORE"+i+".setText(answerStoration.retrieveDataChoices("+j+",TB).get("+k+"));");
k = (k + 1)%4;
if( k == 0) {
j = (j+1) % 11;
}
}
}
}
output:
quizAnswerSTORE0.setText(answerStoration.retrieveDataChoices(1,TB).get(0));
quizAnswerSTORE1.setText(answerStoration.retrieveDataChoices(1,TB).get(1));
quizAnswerSTORE2.setText(answerStoration.retrieveDataChoices(1,TB).get(2));
quizAnswerSTORE3.setText(answerStoration.retrieveDataChoices(1,TB).get(3));
quizAnswerSTORE4.setText(answerStoration.retrieveDataChoices(2,TB).get(0));
quizAnswerSTORE5.setText(answerStoration.retrieveDataChoices(2,TB).get(1));
quizAnswerSTORE6.setText(answerStoration.retrieveDataChoices(2,TB).get(2));
quizAnswerSTORE7.setText(answerStoration.retrieveDataChoices(2,TB).get(3));
quizAnswerSTORE8.setText(answerStoration.retrieveDataChoices(3,TB).get(0));
quizAnswerSTORE9.setText(answerStoration.retrieveDataChoices(3,TB).get(1));
quizAnswerSTORE10.setText(answerStoration.retrieveDataChoices(3,TB).get(2));
quizAnswerSTORE11.setText(answerStoration.retrieveDataChoices(3,TB).get(3));
...
quizAnswerSTORE38.setText(answerStoration.retrieveDataChoices(10,TB).get(2));
quizAnswerSTORE39.setText(answerStoration.retrieveDataChoices(10,TB).get(3));
Try to be consistent with your indentation and line up closing brackets '}' with their corresponding statement.
The first problem I see with this code is that k is never incremented inside the while loop so it will always have the same value and loop forever. The second problem I see is that k is not reset after the while loop so when it goes through the loop the first time (and is correctly incremented) it will stay at a value of 4 and the loop will be skipped every time after that.
I'm not sure what you're trying to achieve (I could use some more information or a sample output) but to begin with you can correct the loop error by changing the while loop to a for loop like so.
for (int i = 0; i < quizAnswerSTORE.size(); i++) {
for (int j = 1; j < 11; j++) {
for (int k = 0; k < 4; k++) {
quizAnswerSTORE.get(i).setText(answerStoration.retrieveDataChoices(j,TB).get(k));
}
}
}
Alternatively, if you wanted to keep the while loop, you could so it like so.
for (int i = 0; i < quizAnswerSTORE.size(); i++) {
for (int j = 1; j < 11; j++) {
int k = 0; // Set k inside the 2nd loop and it will reset to 0 after the while loop
while(k < 4) {
quizAnswerSTORE.get(i).setText(answerStoration.retrieveDataChoices(j,TB).get(k));
k++; // Shorthand for k += 1 which is shorthand for k = k + 1
}
}
}

How to convert ArrayList to Array 2 dimension in java

I want to convert ArrayList to Array 2-Dimension
I have the code below:
ArrayList<String> arrayList=new ArrayList();
arrayList.add("A")
arrayList.add("B")
arrayList.add("C")
arrayList.add("D")
arrayList.add("E")
arrayList.add("F")
int nSize=0,n3item=0, remain=0;
nSize=arrayList.size();
n3item=nSize/3;
remain=nSize%3;
String[][] array[n3item][3]
I want to convert ArrayList to array for example
array[0][1]="A"
array[0][2]="B"
array[0][3]="C"
array[1][1]="D"
array[1][2]="E"
array[1][3]="F"
Now I haven't a solution to do this.
In case of remain is not 0. How to give a solution to this problem
I need your help.
Thanks.
You can use a simple nested for-loop to achieve this.
int numCol = 3;
int numRow = (int) Math.ceil(arrayList.size() / ((double) numCol));
String[][] array = new String[numRow][numCol];
int i, j;
for (i = 0; i < numRow; i++) {
for (j = 0; j < 3 && (i * numCol + j) < arrayList.size(); j++) {
array[i][j] = arrayList.get((i * numCol) + j);
}
}
numRow is found by taking the ceil of number of elements in the list divided by num of desired columns.
eg - when arraylist has 7 elements, numRow will be ceil(7/3.0) = 3.
The main trick here is in the inner for-loop condition (i * numCol + j) < arrayList.size(). It enables us to terminate the loop for the condition remain != 0 you mentioned.
Try to think, how you can fill the 2D array with arraylist values. You need to use a nested loop for assigning the values into the 2D array. Outer loop will iterate over the rows and inner loop will fill the values into each 1D array.
int index = 0;
for(int i = 0; i < n3item; i++) {
for(int j = 0; j < 3; j++) {
array[i][j] = arrayList.get(index);
index++;
}
}

Replaceing a specific number from an int array

Let's say I have an array
int[] array={1,2,3,1,6,3,1};
and I want to replace all the 1 with 4. Are there any ways to do that besides changing it to a string array and use replace, then change it back?
Just loop through the array and swap out any 1's with 4's.
for (int i = 0; i < array.length; i++) {
if (array[i]==1) {
array[i]=4;
}
}
Loop through the array and check each element for the value you are looking for.
for (int i = 0; i < array.length; i++) {
if (array[i] == 1)
array[i] = 4;
}

How to create multiple arrays with a loop?

I am having trouble creating multiple arrays with a loop in Java. What I am trying to do is create a set of arrays, so that each following array has 3 more numbers in it, and all numbers are consecutive. Just to clarify, what I need to get is a set of, let's say 30 arrays, so that it looks like this:
[1,2,3]
[4,5,6,7,8,9]
[10,11,12,13,14,15,16,17,18]
[19,20,21,22,23,24,25,26,27,28,29,30]
....
And so on. Any help much appreciated!
Do you need something like this?
int size = 3;
int values = 1;
for (int i = 0; i < size; i = i + 3) {
int[] arr = new int[size];
for (int j = 0; j < size; j++) {
arr[j] = values;
values++;
}
size += 3;
int count = 0;
for (int j : arr) { // for display
++count;
System.out.print(j);
if (count != arr.length) {
System.out.print(" , ");
}
}
System.out.println();
if (i > 6) { // to put an end to endless creation of arrays
break;
}
}
To do this, you need to keep track of three things: (1) how many arrays you've already created (so you can stop at 30); (2) what length of array you're on (so you can create the next array with the right length); and (3) what integer-value you're up to (so you can populate the next array with the right values).
Here's one way:
private Set<int[]> createArrays() {
final Set<int[]> arrays = new HashSet<int[]>();
int arrayLength = 3;
int value = 1;
for (int arrayNum = 0; arrayNum < 30; ++arrayNum) {
final int[] array = new int[arrayLength];
for (int j = 0; j < array.length; ++j) {
array[j] = value;
++value;
}
arrays.add(array);
arrayLength += 3;
}
return arrays;
}
I don't think that you can "create" arrays in java, but you can create an array of arrays, so the output will look something like this:
[[1,2,3],[4,5,6,7,8,9],[10,11,12,13...]...]
you can do this very succinctly by using two for-loops
Quick Answer
==================
int arrays[][] = new int[30][];
for (int j = 0; j < 30; j++){
for (int i = 0; i < (j++)*3; i++){
arrays[j][i] = (i++)+j*3;
}
}
the first for-loop tells us, via the variable j, which array we are currently adding items to. The second for-loop tells us which item we are adding, and adds the correct item to that position.
All you have to remember is that j++ means j + 1.
Now, the super long-winded explanation:
I've used some simple (well, I say simple, but...) maths to generate the correct item each time:
[1,2,3]
here, j is 0, and we see that the first item is one. At the first item, i is also equal to 0, so we can say that, here, each item is equal to i + 1, or i++.
However, in the next array,
[4,5,6,7,8,9]
each item is not equal to i++, because i has been reset to 0. However, j=1, so we can use this to our advantage to generate the correct elements this time: each item is equal to (i++)+j*3.
Does this rule hold up?
Well, we can look at the next one, where j is 2:
[10,11,12,13,14...]
i = 0, j = 2 and 10 = (0+1)+2*3, so it still follows our rule.
That's how I was able to generate each element correctly.
tl;dr
int arrays[][] = new int[30][];
for (int j = 0; j < 30; j++){
for (int i = 0; i < (j++)*3; i++){
arrays[j][i] = (i++)+j*3;
}
}
It works.
You have to use a double for loop. First loop will iterate for your arrays, second for their contents.
Sor the first for has to iterate from 0 to 30. The second one is a little less easy to write. You have to remember where you last stop and how many items you had in the last one. At the end, it will look like that:
int base = 1;
int size = 3;
int arrays[][] = new int[30][];
for(int i = 0; i < 30; i++) {
arrays[i] = new int[size];
for(int j = 0; j < size; j++) {
arrays[i][j] = base;
base++;
}
size += 3;
}

Issue with ArrayIndexOutOfBoundsException

Running this code gives me an array out of bounds exception at the line:
int sum = array[k]+array[l]; //sum of l and k
...Should be a simple fix, but I can't figure out what could be causing it, given I'm using array.length to bound the loop. Can anyone help?
P.S. For the record, this code is supposed to search an int array for pairs of ints or single ints that equal to a target int. It works using solely the println's, but I'm trying to put the numbers that add up to the target into vectors.
public Vector<Vector<Integer>> subsetSum(int[] array, int target) {
//creates vectors, adds inner vector to another vector
outer = new Vector<Vector<Integer>>();
inner = new Vector<Integer>();
outer.add(inner);
for (int k = 0; k <= array.length; k++) {
for (int l = 0; l <= array.length; l++) {
int sum = array[k]+array[l]; //sum of l and k
int i = 0;
if (sum == target) {
inner.add(i, array[l]);
inner.add(i, array[k]);
i++;
//prints combination
System.out.println(array[l]+"+"+array[k]+"="+target);
}
if (k == target) {
inner.add(i, array[k]);
i++;
//prints if int equals target
System.out.println(k+"="+target);
}
if (l == target) {
inner.add(i, array[l]);
i++;
//prints if int equals target
System.out.println(l+"="+target);
}
}
}
//return combinations that add up to target in vector form
System.out.println(outer);
return outer;
}
You need to use "<" instead of "<=" in your for loops.
Since the first position in the array is 0, the last position is length-1. What's happening is that when you reach the last iteration, the index is already out of the bounds of the array.
For instance, if you have an array:
array = [0,1,2,3] the last iteration would be array[4], the length of the array, which is out of the bounds.
the <= should be replaced with <
Change your loops to be:
for (int k = 0; k < array.length; k++)
and
for (int l = 0; l < array.length; l++)
Since arrays are 0-based, you want to go 1 less than the length.

Categories

Resources