【发布时间】: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