[英]Why the last loop is not working as I expected in Java?
我試圖在 Java 中解決這個問題。 但是,最后一個循環沒有像我預期的那樣工作。 現在,我想知道為什么這不起作用。
將數組作為用戶的輸入。 搜索給定的數字 x 並打印它出現的索引。
package core_java.arrays;
import java.util.Scanner;
import static java.lang.System.in;
import static java.lang.System.out;
public class Java_Array_Exercise {
public static void main(String[] args) {
Scanner sc = new Scanner(in);
// taking the array size
out.print("Enter the size of an array: ");
int size = sc.nextInt();
// Designing the array
int[] arr = new int[size];
// Design of the array input
int pointer = 1;
for (int i = 0 ; i < size ; i++) {
if (pointer == 1) {
out.printf("Enter %dst number: ", pointer);
arr[i] = sc.nextInt();
} else if (pointer == 2) {
out.printf("Enter %dnd number: ", pointer);
arr[i] = sc.nextInt();
} else if (pointer == 3) {
out.printf("Enter %drd number: ", pointer);
arr[i] = sc.nextInt();
} else {
out.printf("Enter %dth number: ", pointer);
arr[i] = sc.nextInt();
}
pointer++;
} // end of array input loop
// target number
out.print("Enter a target from the input: ");
int target = sc.nextInt();
// matching the target design
for (int i = 0 ; i < arr.length ; i++) {
if (arr[i] == target) {
out.printf("Target = %d has found at the index of %d", target, i);
break;
} else if (arr[arr.length - 1] != target ){
out.printf("Your target = %d has not been found.", target);
break;
}
} // end of matching the target loop
} // main method
} // class
最后一個循環沒有按我預期的那樣工作。 第一個和最后一個目標工作正常。 但是,中間目標不起作用。
樣品 output:
Enter the size of an array: 3
Enter 1st number: 1
Enter 2nd number: 2
Enter 3rd number: 3
Enter a target from the input: 2
Your target = 2 has not been found.
以下條件意味着最后一個值不是您循環的值,這不是停止尋找您的值的理由。 因為它不是第一個,也不是最后一個,所以你的站,但沒有在中間搜索
else if (arr[arr.length - 1] != target) {
out.printf("Your target = %d has not been found.", target);
break;
}
您需要先搜索整個數組,然后才能說“未找到”
boolean found = false;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == target) {
out.printf("Target = %d has found at the index of %d\n", target, i);
found = true;
break;
}
}
if (!found) {
out.printf("Your target = %d has not been found.\n", target);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.