簡體   English   中英

Java-將返回布爾值和索引的int數組

[英]Java - An array of int that will return Boolean and the index

java是否有辦法檢查指定用戶輸入的整數數組並返回布爾值以及它所在的索引? 我有辦法,但我也想知道它找到了確切的整數是哪個索引

代碼段:

int numUser = Integer.parseInt(inputUser);
boolean ispresent = false;

for(int x = 0; x<=4; x++){
    if(sum[x] == numUser){
        ispresent = true;
    }else{
        ispresent = false;
    }
}

if(ispresent== true){
    System.out.println("The number is in the array");
}else{
    System.out.println("The number is not in the array");
}

當在數組中找不到它時,您可能會返回-1。 由於數組中沒有-1索引,因此可以說它沒有出現在數組中。

如果該值確實出現在數組中,則可以返回該索引。 由於您總是返回int。

您的問題是非常典型的indexOf()。 通常沒有找到元素時返回-1,否則返回索引(大於或等於0)。

您有不同的方法來獲得該結果。

將數組轉換為列表

int numUser = Integer.parseInt(inputUser);
int index = Arrays.asList(sum).indexOf(numUser);
if (index < 0) {
    System.out.println("The number is not in the array");
} else {
    System.out.println("The number is in the array: " + index);
}

使用Apache ArrayUtils

int numUser = Integer.parseInt(inputUser);
int index = ArrayUtils.indexOf(sum, numUser);
if (index < 0) {
    System.out.println("The number is not in the array");
} else {
    System.out.println("The number is in the array: " + index);
}

自己寫

int numUser = Integer.parseInt(inputUser);
int index = -1;
for (int i = 0; i < sum.length; ++i) {
    if (sum[i] == numUser) {
        index = i;
        break;
    }
}
if (index < 0) {
    System.out.println("The number is not in the array");
} else {
    System.out.println("The number is in the array: " + index);
}

如果您不介意轉換為List ,那么我將使用第一種方法(具有最少依賴性的更清晰的代碼)。 如果您介意並已在項目中使用Apache Utils,則第二種方法很好,並避免進行轉換。 如果您希望保留盡可能少的依賴關系並且可以使用更復雜的源代碼,那么第三個方法可能就是您想要的!

您可以使用:

int result = Arrays.asList(array).indexOf(value);
boolean contained = result != -1;

結果為-1表示該值不在數組中; 如果結果> = 0,則為實際索引。

采用

int numUser = Integer.parseInt(inputUser);
int indexOfNumUser = Arrays.asList(sum).indexOf(numUser);

如果numUser存在,那么indexOfNumUser包含在陣列中的NUM的索引。 如果不是,則包含-1。

如果沒有使用Integers數組,也可以嘗試將其替換為ArrayList。 這將使您的任務更容易解決。

嚴格在“標准” Java中,應該使用之前發布的答案(轉換為List並使用indexOf )。 但是,如果要堅持使用Array,請使用ApacheCommons ArrayUtils.indexOf(int [],int)

從文檔中:

Returns:
the index of the value within the array, INDEX_NOT_FOUND (-1) if not found or null array input

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM