java - 当在 foreach 循环中找不到值时无法找出 println 语句

标签 java arrays

目前正在学习编程基础类(class),我在完成代码时遇到了一些问题。我知道这太草率了,但我花了很多时间试图解决这个问题。除了最后的 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.");
    }

这对我来说似乎不太正确,因为看起来您只想在您无法在未排序和已排序数组中找到该值时将其打印出来。

相反,我建议在所有 for 循环之前创建一个 boolean 并将其设置为 false...如果您在任一数组中找到该值,请将其设置为 true!

最后,更改最后的 if 语句以检查我们是否在数组中找到了值。 (即如果 boolean 为 true。)

关于java - 当在 foreach 循环中找不到值时无法找出 println 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58567519/

相关文章:

c - C中的数组或数组元素?

java - 重复扫描仪临时创可贴? ( java )

java - 识别文件中的音频样本

arrays - 如何从 Swift 2.0 获取子数组

c++ - 如何在 C++ 中打印二维数组?

c - 在 C 中对递增列表进行排序

linear-regression - Java非负多元线性回归库

java - 在使用变量时尝试在 "for"循环中确定 array.length

java - 透明渐变工具栏

javascript - json_encoding 一个数组,但输出为字符串