【问题标题】:How to set flags in java如何在java中设置标志
【发布时间】:2019-04-10 03:31:12
【问题描述】:

我需要编写一个程序,询问用户数组大小,然后用户将输入这些值。之后,我需要让用户删除其中一个值,程序将用零替换它。所以我需要在 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();
}

}

【问题讨论】:

  • 但不起作用 - 究竟什么不起作用?
  • 你的值数组在哪里?你不是在更新数组,你只是在更新“i”变量。
  • 在您的代码中您注释了 将元素向右移动。这不在您对问题的描述中......
  • 这是家庭作业吗?如果是这样,请阅读How do I ask and answer homework questions?。请理解,stackoverflow 是为了帮助人们编程,而不是为他们编程。

标签: java arrays loops boolean flags


【解决方案1】:

仅在循环内使用此代码:

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

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

【讨论】:

    猜你喜欢
    • 2013-08-22
    • 1970-01-01
    • 2016-01-25
    • 2015-07-21
    • 2011-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-22
    相关资源
    最近更新 更多