Using your knowledge on repetition structures (while, do, and for loops), create
ID: 440094 • 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.
Requirements:
A) Use a repetition structure (while, do, or for) as appropriate
B) Read in values from the user until the user types -1
C) If the value entered each time through the loop is even, add it to the sum
D) Display the sum outside of the loop, whenever the user types -1 (be sure not to include the -1 in the sum)
E) Modify the program to read in the values from a text file and display the sum of the even numbers. Create this data file yourself and fill it with values. (this requirement is optional)
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
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.