Write a Java program that 1. first reads an input text file and stores the prime
ID: 3883050 • Letter: W
Question
Write a Java program that
1. first reads an input text file and stores the prime numbers in the file in a hash map;
2. until the program is terminated, the program reads an input number from the user and checks if the number is a prime number stored in the hash map: if the answer is yes the program outputs "HIT", otherwise "MISS" to the console.
For the input file, use the provided input text file INPUT.txt attached. INPUT.txt contains one prime number per line. Your program should read the file from its current path
Explanation / Answer
Hi, I have implemented required program.
Since you have not posted INPUT.txt file so i can not test.
Please let me know in case of any issue.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Scanner;
public class PrimeNumber {
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(System.in);
// opening input file
Scanner fileReader = new Scanner(new File("INPUT.txt"));
// creating HashMap
HashMap<Integer, Integer> hashMap = new HashMap<>();
// reading all integers from file and storing in hashmap
while(fileReader.hasNextInt()) {
int num = fileReader.nextInt();
if(hashMap.containsKey(num)) {
hashMap.put(num, 1);
}
}
fileReader.close();
// taking user input
int input;
System.out.println("Enter number to check( 0 to stop)");
input = sc.nextInt();
while(input != 0) {
if(hashMap.containsKey(input))
System.out.println("HIT");
else
System.out.println("MISS");
System.out.println();
input = sc.nextInt();
}
sc.close();
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.