[英]java comparing values in arrays
不確定是否要創建新線程。 但我會在這里發布。 我覺得我的解釋不是很好。
我下面有一個課
假設int [] = 1204,1205
public class Job {
private int[] serviceCode =;
public Job (int[] jobCode) {
serviceCode = jobCode;
}
public int[] getJobCode() {
return serviceCode;
}
這是主程序
public class MainProgram {
public static void main {
}
}
如何將數組的值放入單獨的整數?
您不能直接將int[]
與int
進行比較。 您需要訪問數組中的值,然后進行比較。
int[] myArray = {1, 2, 3};
int value = 1;
if (myArray[0] == value) {/*do something*/}
您不能將數組與僅包含一個數據的變量進行比較。
您知道,數組是一種數據結構。
您必須遍歷數組,然后將數組的每個值與t
進行比較。
for(int i = 0; i < h.length; i++) {
if( t == h[i] ) // Or any other comparison operator
/* Perform some action.*/;
}
您的int[] h
是一個整數數組,而int t
只是一個整數變量。 因此,根本不可能進行比較。 根據您問題的標題, java comparing values in arrays
是一個答案。
您可以在for
循環中檢查此值是否存在於數組中。
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
}
}
數組是連續的內存位置,為了從每個可尋址單元中獲取特定值,您必須訪問該可尋址位置。 假設您聲明一個像這樣的數組。
int[] array = {10,20,30};
這將像這樣進行內存分配:(讓0th
元素位於地址100
並假設int大小為4 byte
)
index 0 1 2
-----------------------
| 10 | 20 | 30 |
-----------------------
address: 100 104 108
數組array
名稱基本上是基址格式,在這種情況下,數組的起始位置是100
,下一個元素將出現在104
和108
。
現在,我們有一個整數變量: int temp=100
。 現在要比較具有整數變量temp
數組元素,我們必須訪問位於特定索引處的integer類型的array
的每個元素。 您必須進行如下比較:
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.
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.