In: Computer Science
Java Programming
create a program that calculates the average of the prime values in the file.
Process:
"Values.txt"
751
1090
971
1054
7
300
19
834
100
751
549
288
641
989
479
1388
1319
584
Code Outline:
public class ChapterSixMain {
public static void main(String[] args) {
// Read Lines from
"Values.txt"
// Determine if the line is an
integer
// Determine if the integer is
prime
// Keep running average of
primes
// Print running average of primes
(no formatting necessary)
}
}
Example 1:
| Values.txt | Prime Values | Average |
| 751 1090 971 1054 7 300 19 834 100 751 549 288 641 989 479 1388 1319 584 |
751 971 7 19 751 641 479 1319 |
617.2499999999999 |
| Values.txt | Prime Values | Average |
| 61 121 124 479 Blackberry 787 416 541 1011 Lemon 1051 493 827 140 Jackfruit 1103 Mango Blackberry 113 Blackberry 439 Orange Kiwi 1103 562 504 |
61 479 787 541 1051 827 1103 113 439 1 |
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ChapterSxiMain {
public static void main(String[] args) throws FileNotFoundException {
FileInputStream fis = new FileInputStream("E://values.txt");
Scanner sc = new Scanner(fis);
double avg = 0;
int numOfelement = 0, sum = 0;
// Read Lines from values.txt
while (sc.hasNextLine()) {
// Determine if line is integer
try {
int val = Integer.parseInt(sc.nextLine());
int count = 0;
// Determine if integer is prime
for (int i = 2; i <= val / 2; i++) {
if (val % i == 0)
count++;
}
if (count == 0) {
sum += val;
numOfelement++;
}
// Keep running average of prime
} catch (Exception e) {
}
}
// Print Average of prime
System.out.println(sum * 1.0 / numOfelement);
sc.close();
}
}
Screenshot for reference understanding:

Do UPVOTE, if you found solution helpful!!