繁体   English   中英

如何在java中设置标志

[英]How to set flags in java

我需要编写一个程序,询问用户数组大小,然后用户将输入这些值。 之后,我需要要求用户删除这些值之一,程序将用零替换它。 所以我需要在 for 循环中写一个 if 语句来检查用户输入的数字是否在数组中找到,或者是否用零替换它。 但是我需要使用一个布尔值和一个标志,我不知道该怎么做。 到目前为止,我得到了这个,但不起作用。

System.out.println("Enter the value to search and remove: ");
        // Use your Scanner to get a value for search
         int valueToRemove = scan.nextInt();

    // To search, we can iterate all values, record the index of target (t),
    // and then shift to the left values from t to the end.
    boolean isFound = false;
    for (int i = 0; i < arraySize; i++)
    {
         if (i == valueToRemove){

         }
        //     Set a flag isFound
        // 
        if (isFound = true) {
        //     if i + 1 is available
        //         move element i + 1 to index i
            i = (i+1);
        }
        //     if i + 1 is not available
         else
        //         set element i as zero
         i=0;
    }

    if (isFound)
    {
        System.out.println("Search element found");
    }
    else
    {
        System.out.println("Search element NOT found");   
    }


    // ============================================================
    // Display the final array

    System.out.println("\nThe final array");

    for (int i = 0; i < arraySize; i++)
    {
        // Print ith element, do NOT include line break
        System.out.print(integerArray[i]+ ", " );
    }

    // Print a line break
    System.out.println();
}

}

在循环内仅使用此代码:

isFound = (a[i] == valueToRemove);
if (isFound) {
    a[i] = 0;
    break;
}

isFound是标志和它得到true ,如果数组项a[i]是等于valueToRemove
如果此标志为true ,则将项目的值更改为 0 enter code here并退出循环。
我使用a作为数组,将其更改为变量的名称。
我猜arraySize是一个保存数组大小的变量。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM