Java: please make sure code compiles and runs before posting. Write a program th
ID: 3585450 • Letter: J
Question
Java: please make sure code compiles and runs before posting.
Write a program that reads from the attached text file called Logic.txt one word at a time. The program counts how many words start with the letters "is" (use startsWith method from String class to check for that), and prints each word with all the vowels replaced with ~ character (use replaceAll method from String class to replace all the vowels with the given replacement String). At the end, the program outputs the count of all the words that start with "is". See the expected output below:
"C~ntr~r~w~s~," c~nt~n~~d Tw~~dl~d~~, "~f ~t w~s s~, ~t m~ght b~; ~nd ~f ~t w~r~ s~, ~t w~~ld b~; b~t ~s ~t ~sn't, ~t ~~nt't. Th~t ~s l~g~c."
2 words start with "is".
Logic.txt content:
Explanation / Answer
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
class Main {
public static void main(String args[]) {
Scanner sc = null;
int iscount = 0;
String replacementString = "~";
try {
// read file
sc = new Scanner(new File("Logic.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//read each word
while (sc.hasNext()) {
String s = sc.next();
//if words starts with is increment iscount
if (s.startsWith("is")) {
iscount++;
}
// replace all vowels with replacementString
s = s.replaceAll("[aeiou]", replacementString);
System.out.print(s);
}
System.out.println();
System.out.println(iscount + " words starts with "is"");
}
}
/*
"C~ntr~r~w~s~,"c~nt~n~~dTw~~dl~d~~,"~f~tw~ss~,~tm~ghtb~;~nd~f~tw~r~s~,~tw~~ldb~;b~t~s~t~sn't,~t~~nt't.Th~t~sl~g~c."
2 words starts with "is"
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.