In java how would you write a project where a user types in the date of an event
ID: 673406 • Letter: I
Question
In java how would you write
a project where a user types in the date of an event no dashes (EX:12252015)
that reads the file the user would saved as (EX. 12252015.txt)
searches for a word of phrase (merry) that is in code backwards and every two letters are to be neglected
tells the user how many times the phrase was stated in the document
example text file: ynnrnnrnnennmnn ynnrnnrnnennm nnynnrnnrnnennmnn
what's read on the file is: merry merry merry
Example output:
Please the date including the year: 12252015
Opening File:12252015.txt
Enter word or phrase: merry
The phrase merry was found 3 times.
Do you wish to continue (y) or (no)
Explanation / Answer
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReadFileAndCountStrings {
public static void main(String args[]) {
try {
Scanner scanner = new Scanner(System.in);
while (true) {
// Get the filename.
System.out.print("Please the date including the year: ");
String filename = scanner.nextLine();
// Open the file.
File file = new File(filename + ".txt");
Scanner inputFile = new Scanner(file);
System.out.println("Opening File:" + filename + ".txt");
System.out.print("Enter word or phrase: ");
String word = scanner.nextLine();
int totalNoofTimes = 0;
// Read lines from the file until no more are left.
while (inputFile.hasNext()) {
// Read the next name.
String strLine = inputFile.nextLine();
// Display the last name read.
totalNoofTimes += countString(strLine, word);
}
System.out.println("The phrase merry was found "+totalNoofTimes+" times.");
// Close the file.
inputFile.close();
System.out.print("Do you wish to continue (y) or (no):");
String continueStatus = scanner.nextLine();
if (!continueStatus.equals("y")) {
break;
}
}
scanner.close();
} catch (FileNotFoundException e) {
// TODO: handle exception
System.out.println("File Not Found ");
} finally {
}
}
public static int countString(String string, String find) {
String in = string;
int i = 0;
Pattern p = Pattern.compile(find);
Matcher m = p.matcher(in);
while (m.find()) {
i++;
}
return i;
}
}
output:
Please the date including the year: 122015
Opening File:122015.txt
Enter word or phrase: merry
The phrase merry was found 3 times.
Do you wish to continue (y) or (no):y
Please the date including the year: 122015
Opening File:122015.txt
Enter word or phrase: merry1
The phrase merry was found 0 times.
Do you wish to continue (y) or (no):no
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.