How to set flags in java

I need to write a program that asks the user for array size and then the user will input these values. After that, I need to ask the user to remove one of those values and the program will replace it with a zero. SO i need to write an if statement inside a for loop to check if the number the user inputed is found in the array or not the replace it with a zero. However i am required to use a boolean and a flag and im not sure how to do that. so far i got this but does not work.

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(); } 

}

4

1 Answer

Inside the loop use this code only:

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

isFound is the flag and it gets true if the array item a[i] is equal to valueToRemove.
If this flag is true it changes the value of the item to 0 enter code hereand exits the loop.
I used a for the array, change it to the name of your variable.
I guess arraySize is a variable holding the size of the array.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like