Reputation: 63
Wasn't sure whether to make a new thread or not. but i'll post it here. I figured my explanation was not very good.
i have a class below
lets say int[] = 1204, 1205
public class Job {
private int[] serviceCode =;
public Job (int[] jobCode) {
serviceCode = jobCode;
}
public int[] getJobCode() {
return serviceCode;
}
and this is the main program
public class MainProgram {
public static void main {
}
}
how do i put the values of the array into separate integers?
Upvotes: 0
Views: 22816
Reputation: 2067
Array is contiguous memory location, in order to get the specific values from the each addressable unit you have to access that addressable location. Suppose you declare an array like this.
int[] array = {10,20,30};
This will do the memory allocation like this: ( lets 0th
element is at address 100
and assuming int size is of 4 byte
)
index 0 1 2
-----------------------
| 10 | 20 | 30 |
-----------------------
address: 100 104 108
Array array
name is basically base address form where the array starts in this case it is 100
, next element will be present at 104
and 108
.
Now lets say we have an integer variable : int temp=100
. Now to compare array element with integer variable temp
, we have to access the each element of array
of type integer situated at specific index. You have to compare like following:
for(int i=0; i<array.length; i++){
if(temp>array[i]) /*array[i] is accessing the value at index i"*/
//do something
else
//do something.
}
Upvotes: 0
Reputation: 7490
Your int[] h
is an array of integers while int t
is just a integer variable. So comparison is not at all possible. As per your question's title java comparing values in arrays
here is an answer.
Either you can check whether this value exist in an array in for
loop.
int val = 1;
int[] valArray = {1,2,3,4,5};
for(int i = 0; i < valArray.length ; i++)
{
if (valArray[i] == val)
{// Matched
}
else
{ // Not matched
}
}
Upvotes: 1
Reputation: 2453
You cannot compare an array with a variable that holds just one data.
You know, array is a data structure.
You must loop through the array and then compare each value of the array with t
.
for(int i = 0; i < h.length; i++) {
if( t == h[i] ) // Or any other comparison operator
/* Perform some action.*/;
}
Upvotes: 2
Reputation: 1375
You can't directly compare an int[]
to an int
. You need to access a value in the array and then compare.
int[] myArray = {1, 2, 3};
int value = 1;
if (myArray[0] == value) {/*do something*/}
Upvotes: 3