Free Response Practice Question (with solution)- Even Number Array
<-- Back to AP CSA Exam Solutions | Next to Increasing Order Array --> |
Even Number Array
Write a Java program that reads numbers from the user and stores them in an array. The array stores only even numbers. If the number entered by the user is not even, an appropriate message is displayed and the user is asked to enter more (even) numbers. Once 10 even numbers are stored in the array, the program should display all the numbers.
Solution:
import java.util.InputMismatchException; import java.util.Scanner; public class EvenNumberArray { public static void main(String[] args) { int SIZE =10; int[] evenArr = new int[SIZE]; int i=0; try (Scanner input = new Scanner(System.in)) { int number; char choice; do { System.out.print("Enter a even number: "); number = input.nextInt(); if(number %2 == 0) // even number { evenArr[i] = number; i++; } else { System.out.println("You must enter an even number only!"); System.out.println("There are still "+ (SIZE -i) + " numbers to be entered"); } System.out.print("Do you want to continue y/n? "); choice = input.next().charAt(0); }while ((choice=='y' || choice == 'Y') && (i< SIZE)); System.out.println("There are currently "+ i + " numbers in the array"); for (int k=0; k < i; k++) { System.out.print(evenArr[k]+ " "); } } catch (InputMismatchException e) { System.out.println("Error reading input"); } } }
Java project file:
<-- Back to AP CSA Exam Solutions | Next to Increasing Order Array --> |