Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Using your knowledge on repetition structures (while, do, and for loops), create

ID: 440093 • Letter: U

Question

Using your knowledge on repetition structures (while, do, and for loops), create a small Java program that uses all of these concepts. To begin, write a program that reads in numbers from the user until they enter a -1 value; this program should sum all the values only if the value is even (i.e., if the user enters an odd number, ignore it). Then, modify this program to read the input from a file instead of the user.

As a hint, realize that if a number is even, then the integer remainder when it is divided by 2 will equal 0, so if the value is n, then n % 2 will equal 0.

Explanation / Answer

RepetionTest.java import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class RepetionTest { public static void main(String[] args) { Scanner inScanner = new Scanner(System.in); int sum = 0; //using while loop while(true) { System.out.println("Enter a no. (To exit enter -1):"); int n = inScanner.nextInt(); if(n==-1) break; else if(n%2==0) sum += n; } System.out.println("Sum when read from keyboard is " + sum); fileTest(); } public static void fileTest() { try { Scanner inScanner = new Scanner(new File("C:\Cramster\RepetionTest\src\data.txt")); int sum = 0; //using do-while do { int n = inScanner.nextInt(); if(n==-1) break; else if(n%2==0) sum += n; }while(true); System.out.println("Sum when read from a file is " + sum); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } Output: Enter a no. (To exit enter -1): 1 Enter a no. (To exit enter -1): 4 Enter a no. (To exit enter -1): 2 Enter a no. (To exit enter -1): 5 Enter a no. (To exit enter -1): 7 Enter a no. (To exit enter -1): 8 Enter a no. (To exit enter -1): -1 Sum when read from keyboard is 14 Sum when read from a file is 20