I am searching for matching elements in two arrays. If the matching element was found I set k and j greater than the for loop conditions to quit the cycle, but I get an exception at inner loop condition. Granted, I can fix it by using break outerloop;, but isn't setting index greater than the for loop condition supposed to exit the loop?
//outerloop:
for (int j = 0; j < listOfSubcategories.size(); j++) {
if (listOfSubcategories.get(j).subcatName.equals(rawOptions.get(i).subcatName)) { //if the subcatName exists
for (int k = 0; k < listOfSubcategories.get(j).listOfID.size(); k++) {
if (0 == rawOptions.get(i).codeID.compareTo(listOfSubcategories.get(j).listOfID.get(k).codeID)) {//if this id (as in 0090-01 exists
listOfSubcategories.get(j).listOfID.get(k).usageCount += rawOptions.get(i).usageCount;
isProcessed = true;
k=listOfSubcategories.get(j).listOfID.size(); //this fails
j = listOfSubcategories.size();
//break outerloop; //this works
}
}
}
}
First of all, can you please post your stack trace?
Second, your exception is most likely caused by j = listOfSubcategories.size(); This makes comparison k < listOfSubcategories.get(j).listOfID.size() impossible.
The code below works.
public class ForArray {
public static void main(String[] args) {
int[] myIntArray = {1, 2, 3}; //This is my Array
int searchingForThisNumberInArray = 2; //Search for this number in an array
int index=-1; //Index of the first matching element. -1 if element not found.
for (int i = 0; i < myIntArray.length; i++) { //Check each element
if (myIntArray[i] == searchingForThisNumberInArray) { //if this element contains correct number
index = i; //Save it in index
i = myIntArray.length; //Quit for cycle by increasing i.
}
}
System.out.println(index);
}
}
Related
Say I have an array of:
int [] I = { 1, 3, 6, 3, 7,3, 9, 3};
int value = 3;
I have a for loop that tracks the amount of occurences of the value:
int counter = 0;
for(int x = 0; x < I.length; x++)
{
if(I[x] == value)
{
counter++;
}
}
I make a new array with length equal to the number of occurrences, that can store all the indices of the occurences from the original array:
int [] index = new int [counter];
for(int x = 0; x < index.length; x++)
{
for(int i = 0; i<I.length; i++)
{
if(I[i] == value){
index[x] = i;
}
}
}
However, when I print my array of indices, i just get the last index printed the amount of times counter is equal to, when I want all the indices.
for(int i = 0; i<index.length; i++)
{
System.out.println(index[i]);
}
It just prints "7" (the last index) 3 times. How do I go about fixing this so I have an array of all indices?
Thank you.
Your second for loop should not be nested; you should only increment x when you find a match. Something like,
for (int i = 0, x = 0; i < I.length; i++) {
if (I[i] == value) {
index[x] = i;
x++;
}
}
Assuming you're using Java 8+, you could have written a filter() on the range of indices in the array. Like,
int[] index = IntStream.range(0, I.length).filter(i -> I[i] == value).toArray();
System.out.println(Arrays.toString(index));
Just remove the outer for loop and store into the index array as you iterate through the original array I. The problem with your code is that, since you repeat the iterations once for each index in the index array, you end up with the last found index (7 in your case).
for(int i = 0, x = 0; i < I.length; i++) {
if(I[i] == value) {
index[x++] = i;
}
}
I have a loop to loop through 0-200 and if the number matches the number in the list. I will put it inside the freq[][]. However, I'm having problem into putting the numbers I found into the freq[][] considering that it needs to be in the size of [10][20].
public static void example(List<Integer> numbers, List<Integer> elements, int[][] list){
int index = 0;
int[][] freq = new int[10][20];
for (int i = 0; i < 200; i++){
for (int x = 0; x < list.length; x++){
for (int y = 0; y < list[x].length; y++){
if (list[x][y] == i){
freq[][index] = i;
}
}
}
}
}
Keep it as
if (list[x][y]== i){
freq[x][y] = i;
}
else {
freq[x][y] = 0; // if not matched
}
So that freq will be a two dimensional array with 10rows and 20 columns .
-Element at 5th index position in the list will be in 0*5th position in the 10*20 array.
-Element at 199 th index position in the list will be in 9*19th position in the 10*20 array.
first, you make a loop to read 200 numbers inside this loop you want to loop 2d array to compare its elements by every number and make condition if a number exist in list but it in freq[][] this code put every number Achieves the condition in freq array and otherwise but 0
for (int i = 0; i <= 200; i++) {
for (int j = 0; j < list.length; j++) {
for (int k = 0; k < list[j].length; k++) {
if(list[j][k]==i)
freq[j][k]=i;
}
}
}
if you use `
else
freq[j][k]=0;
`
that mean it start putting in array the number or 0, and finally, you get an array don't match you want, so let if condition only without else I test it and it work for me
I tried writing a Sieve of Eratosthenes algorithm, I am getting an ArrayIndexOutOfBoundsException but I don't seem to understand why, if I change the limits, upon printing it only displays composite numbers, the code's below help if you can.
public static Boolean[] solution(int N) {
Boolean[] isPrime = new Boolean[N];
isPrime[0] = false;
for(int i = 1; i <= N; i++) {
isPrime[i] = true;
}
for(int i = 2; i <= N; i++) {
if(isPrime[i]== true) {
System.out.println(i);
for(int j = 2; (j * i) < N; j++) {
int k = j * i;
isPrime[k] = false;
}
}
}
return isPrime;
i <= N; cause the error
for(int i = 1; i <= N; i++) {
isPrime[i] = true;
}
for example
if N=4 then you get error when i=4. isPrime[4] cause OutOfBounds exception because length is 4.arrays are zero index based. so maximum index you can access is 3.isPrime[3]
you can avoid this error by changing loop to for(int i = 1; i < N; i++) {
however i'm not sure what is Eratosthenes algorithem is .i hope you can change your code keep in mind arrays are zero index based
Boolean[N] creates an array of N elements, so, since the indexes start from 0, the last index is N-1.
The error is caused by i<=N in the for loop
Hi guys I've been learning java over the summer and this is the last assignment, and I'm stuck. The program is supposed to take 13 numbers that I enter, sort them and then find the index number of the greatest number that I input in the original array. I'm trying to see if my selection method works but every time I try to enter in the numbers I get an out of bounds error. This is kind of frustrating and I've been trying to find and answer for a couple of hours now. Any help would be greatly appreciated. Thanks!
import java.util.Scanner;
public class fmax
{
public static void main(String[] args)
{
int indmax;
int[] fmax = new int[13];
fillmax(fmax);
//System.out.println(fmax);
indmax = maxfmax(fmax);
//indmin = minfmax();
System.out.println(indmax);
}
public static void fillmax(int[] farray)
{
Scanner sc = new Scanner(System.in);
int i = 0;
for(i = 0; i < farray.length; i++)
{
farray[i] = sc.nextInt();
}
}
public static int maxfmax(int[] farray)
{
int[] copy = farray;
int j, x=0, i;
boolean flag = true;
int temp;
while(flag)
{
flag = false;
for( j = 0; j < copy.length -1; j++)
{
if(copy[j] < copy[j+1])
{
temp = copy[j];
copy[j] = copy[j+1];
copy[j+1] = temp;
flag = true;
}
}
for(i=0; i <= farray.length; i++)
{
if(farray[i] == copy[1])
x = i;
}
}
return x;
}
}
This line will throw the out of bounds exception.
for(i=0; i <= farray.length; i++)
Your termination condition is incorrect. Try this:
for(i=0; i < farray.length; i++)
so that you stop the loop before you go past the last index (farray.length - 1).
You defined the Lenght of the Array as 13 than you run this line:
for(i=0; i <= farray.length; i++)
This means you will go for the items fmax[13] which doesnt exist, because java starts counting at 0. So the hightest index is fmax[12]. You need to change your condition to something like that:
for(i=0; i < farray.length; i++)
or
for(i=0; i <= farray.length -1; i++)
In this case length for array is returning size of your array - but it starts with 1 not with zero.
i <= farray.length - causes out of bounds exception
u have to use - as was mentioned i < farray.length in your for loop
Array always has index beginning with zero and ending with length-1
for(i=0; i <= farray.length; i++)
Your terminating condition is wrong. It is trying to access element located at index length, which does not exist and hence you get the exception. It should be modified to something like below to make it work:
for(i=0; i < farray.length; i++)
There are many symbol games working in this way so this should sound familiar to you.
Facts:
I have two arrays with same length of 4.
(A[4] and B[4])
I fill them with random integers from 1 to 6.
I can NOT sort them in any way (they must stay the same).
Problems:
I need to compare them and after that I need to have 3 values. FIRST one needs to count how many elements are the same and in the same place. I do it like this and it is working:
int first = 0;
int k = 0;
for (int j=1; j<=4; j++)
{
k++;
if (A[k] == B[j])
{
first++;
}
}
SECOND one needs to count how many elements are the same BUT not at the same place. THIRD one needs to count how many elements are not the same at all.
I need a solution to count either SECOND or THIRD number, because after that I can just subtract like 4-(first+second) or 4-(first+second).
Here's the logic you should use: loop over the first array; for each element, check if the corresponding element of the second array is the same - if yes, increment your first counter. If they are not the same, then check whether the second array contains the corresponding element of the first array. If it does, then it's definitely not in the same position (you just checked same positions) - increment your second count. Otherwise, increment your third count. The code can be as following:
int[] A = {...};
int[] B = {...};
List<Integer> lstB = new ArrayList<Integer>(B.length);
for (int index = 0; index < B.length; index++) {
lstB.add(B[index]);
}
int first = 0, second = 0, third = 0;
for(int i=0; i<4; i++) {
if(A[i] == B[i]) {
first++;
}
else if(lstB.contains(A[i]) {
second++;
}
else {
third++;
}
}
SOLUTION
Eventually I made the right algorithm. In general, the solution is to keep track of what fields you used when counting FIRST value. And here is the code:
int first = 0;
int second = 0;
int third = 0;
boolean[] codeUsed = new boolean[4];
boolean[] guessUsed = new boolean[4];
//same value and same place
for (int i = 0; i < 4; i++)
{
if (A[i] == B[i])
{
first++;
codeUsed[i] = guessUsed[i] = true;
}
}
//same value but not right place
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
if (!codeUsed[i] && !guessUsed[j] && A[i] == B[j])
{
second++;
codeUsed[i] = guessUsed[j] = true;
break;
}
}
}
//not the same value
third = 4 - first - second;