[英]Why the last loop is not working as I expected in Java?
I am trying to solve this question in Java.我试图在 Java 中解决这个问题。 However, the last loop is not working as I had expected.
但是,最后一个循环没有像我预期的那样工作。 Now, I want to know why this is not working.
现在,我想知道为什么这不起作用。
Take an array as input from the user.将数组作为用户的输入。 Search for a given number x and print the index at which it occurs.
搜索给定的数字 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
The last loop is not working as I expected.最后一个循环没有按我预期的那样工作。 1st and last targets are working fine.
第一个和最后一个目标工作正常。 However, middle targets are not working.
但是,中间目标不起作用。
Sample output:样品 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.
The following condition means that the last value isn't the value you loop for, that isn't a reason to stop looking for you value.以下条件意味着最后一个值不是您循环的值,这不是停止寻找您的值的理由。 As it isn't the first, and not the last, your stop, but haven't search in the middle
因为它不是第一个,也不是最后一个,所以你的站,但没有在中间搜索
else if (arr[arr.length - 1] != target) {
out.printf("Your target = %d has not been found.", target);
break;
}
You need to have search through the whole array before being able to say "not found"您需要先搜索整个数组,然后才能说“未找到”
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.