In: Computer Science
Java program
Bounds checking
Make an array {4, 6, 2, 88, 5}, ask the user what number they would like to change. If their pick is out of bounds, tell them. Otherwise ask them what they would like to change the number to. After the change, display all the numbers with a for loop
import java.util.Scanner; public class ChangeArrayElement { public static void print(int[] arr) { for(int i = 0; i < arr.length; ++i) { System.out.print(arr[i] + " "); } System.out.println(); } public static void main(String[] args) { Scanner in = new Scanner(System.in); int[] numbers = {4, 6, 2, 88, 5}; System.out.print("Array is: "); print(numbers); System.out.print("Which number would you like to change? "); int n = in.nextInt(); boolean found = false; for (int i = 0; i < numbers.length; i++) { if (numbers[i] == n) { System.out.print("Enter new value: "); numbers[i] = in.nextInt(); found = true; break; } } if (!found) { System.out.println(n + " is not found in the array"); } else { System.out.print("New Array is: "); print(numbers); } } }