目前在编程基础课程中,我在完成代码方面遇到一些麻烦。我知道这太草率了,但是我花了很多时间试图解决这个问题。除最终的println语句外,其他所有方法均有效。我无法在正确的时间打印出来。即使找到该值,它也始终打印。我知道问题出在最终的if语句中,但老实说我无法弄清楚该放在哪里。谢谢你的帮助。
System.out.print("\n\nPlease enter number to search for: ");
Scanner scan = new Scanner (System.in);
int search = scan.nextInt();
int index = 1;
for (int numb : unsortedArray) {
if (numb == search)
System.out.println("\nSearch Value: " + numb + " is found at location: " + (index) +" in the unsorted array.");
index++;
}
for (int numb : sortedArray) {
if (numb == search)
System.out.println("\nSearch Value: " + numb + " is found at location: " + (index -10) +" in the sorted array.");
index++;
}
if (search != 1) {
System.out.println("Search Value: " + search + " was not found.");
}
最佳答案
问题是您要检查search
变量是否不等于1,其中search
是您从控制台从用户那里收到的输入。
if (search != 1) {
System.out.println("Search Value: " + search + " was not found.");
}
这对我来说似乎不太正确,因为看起来好像您只想在无法在未排序和已排序数组中都找到该值时将其打印出来。
相反,我建议在所有
boolean
循环之前创建一个for
并将其设置为false ...如果在任一数组中找到该值,请将其设置为true!最后,更改最后的
if
语句以检查是否在数组中找到了该值。 (即boolean
为true。)