I've written majority of this. I just can't figure out how to capitalize the first letter of each line. the problem is:
Write a program that checks a text file for several formatting and punctuation matters. The program asks for the names of both an input file and an output file. It then copies all the text from the input file to the output file, but with the following two changes (1) Any string of two or more blank characters is replaced by a single blank; (2) all sentences start with an uppercase letter. All sentences after the first one begin after either a period, a question mark, or an exclamation mark that is followed by one or more whitespace characters.
I've written most of the code. I just need help with the capitalization of the first letter of each sentence. Here's my code:
import java.io.*;
import java.util.Scanner;
public class TextFileProcessor
{
public static void textFile()
{
Scanner keyboard = new Scanner(System.in);
String inputSent;
String oldText;
String newText;
System.out.print("Enter the name of the file that you want to test: ");
oldText = keyboard.next();
System.out.print("Enter the name of your output file:");
newText = keyboard.next();
System.out.println("\n");
try
{
BufferedReader inputStream = new BufferedReader(new FileReader(oldText));
PrintWriter outputStream = new PrintWriter(new FileOutputStream(newText));
inputSent = inputStream.readLine();
inputSent = inputSent.replaceAll("\\s+", " ").trim();
inputSent = inputSent.substring(0,1).toUpperCase() + inputSent.substring(1);
inputSent = inputSent.replace("?", "?\n").replace("!", "!\n").replace(".", ".\n");
//Find a way to make the first letter capitalized
while(inputSent != null)
{
outputStream.println(inputSent);
System.out.println(inputSent);
inputSent = inputStream.readLine();
}
inputStream.close();
outputStream.close();
}
catch(FileNotFoundException e)
{
System.out.println("File" + oldText + " could not be located.");
}
catch(IOException e)
{
System.out.println("There was an error in file" + oldText);
}
}
}
import java.util.Scanner;
import java.io.*;
public class TextFileProcessorDemo
{
public static void main(String[] args)
{
String inputName;
String result;
String sentence;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the name of your input file: ");
inputName = keyboard.nextLine();
File input = new File(inputName);
PrintWriter outputStream = null;
try
{
outputStream = new PrintWriter(input);
}
catch(FileNotFoundException e)
{
System.out.println("There was an error opening the file. Goodbye!" + input);
System.exit(0);
}
System.out.println("Enter a line of text:");
sentence = keyboard.nextLine();
outputStream.println(sentence);
outputStream.close();
System.out.println("This line was written to:" + " " + input);
System.out.println("\n");
}
}
Since your code already contains inputSent = inputSent.substring(0,1).toUpperCase() + inputSent.substring(1); I assume that inputSent can contain more than one sentence or might just represent a line of the file with parts of sentences.
Thus I'd suggest you first read the entire file into a string (if it's not too large) and then use split() on that string to break it into individual sentences, capitalize the first character and join them again.
Example:
String[] sentences = fileContent.split("(?<=[?!.])\\s*");
StringBuilder result = new StringBuilder();
for( String sentence : sentences) {
//append the first character as upper case
result.append( Character.toUpperCase( sentence.charAt(0) ) );
//add the rest of the sentence
result.append( sentence.substring(1) );
//add a newline
result.append("\n");
}
//I'd not replace the input, but to be consistent with your code
fileContent = result.toString();
The easiest way is maybe using WordUtil from Apache commons-langs.
You should use the capitalise method with the delimiters as parameter.
You can try the following regular expression:
(\S)([^.!?]*[.!?]( |$))
Code:
public static void main(String[] args) {
String inputSent = "hi! how are you? fine, thanks.";
inputSent = inputSent.replaceAll("\\s+", " ").trim();
Matcher m = Pattern.compile("(\\S)([^.!?]*[.!?]( |$))").matcher(inputSent);
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, m.group(1).toUpperCase() + m.group(2) + "\n");
}
m.appendTail(sb);
System.out.println(sb);
}
See a demo online.
Output:
Hi!
How are you?
Fine, thanks.
In the ASCII table lower and upper case are just integers that are 32 positions away from each other...
try something like this:
String inputSent = .... //where ever it does come from...
System.out.println(inputSent.replace(inputSent.charAt(0), (char) (inputSent.charAt(0) - 32)));
or use some kind of APACHE libs like WordUtils.
I would change the textFile() to the below:
public static void textFile()
{
Scanner keyboard = new Scanner(System.in);
String inputSent;
String oldText;
String newText;
System.out.print("Enter the name of the file that you want to test: ");
oldText = keyboard.next();
System.out.print("Enter the name of your output file:");
newText = keyboard.next();
System.out.println("\n");
try
{
BufferedReader inputStream = new BufferedReader(new FileReader(oldText));
PrintWriter outputStream = new PrintWriter(new FileOutputStream(newText));
while ((inputSent = inputStream.readLine()) != null) {
char[] chars = inputSent.toCharArray();
chars[0] = Character.toUpperCase(chars[0]);
inputSent = new String(chars);
inputSent = inputSent.replaceAll("\\s+", " ").trim();
inputSent = inputSent.substring(0,1).toUpperCase() + inputSent.substring(1);
inputSent = inputSent.replace("?", "?\n").replace("!", "!\n").replace(".", ".\n");
System.out.println("-> " + inputSent);
outputStream.println(inputSent);
}
inputStream.close();
outputStream.close();
}
catch(FileNotFoundException e)
{
System.out.println("File" + oldText + " could not be located.");
}
catch(IOException e)
{
System.out.println("There was an error in file" + oldText);
}
}
This will read the text file line by line.
Upper the first char
Do this in a while loop
The problem with your original textFile() is that it only applies uppercase first char, blank space etc on the very first line it reads.
Related
I am attempting to write a program that will take user input ( a long message of characters), store the message and search a text file to see if those words occur in the text file. The problem I am having is that I am only ever able to read in the first string of the message and compare it to the text file. For instance if I type in "learning"; a word in the text file, I will get a result showing that is is found in the file. However if I type "learning is" It will still only return learning as a word found in the file even though "is" is also a word in the text file. My program seems to not be able to read past the blank space. So I suppose my questions is, how do I augment my program to do this and read every word in the file? Would it also be possible for my program to read every word, with or without spaces, in the original message taken from the user, and compare that to the text file?
Thank you
import java.io.*;
import java.util.Scanner;
public class Affine_English2
{
public static void main(String[] args) throws IOException
{
String message = "";
String name = "";
Scanner input = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
System.out.println("Please enter in a message: ");
message = scan.next();
Scanner file = new Scanner(new File("example.txt"));
while(file.hasNextLine())
{
String line = file.nextLine();
for(int i = 0; i < message.length(); i++)
{
if(line.indexOf(message) != -1)
{
System.out.println(message + " is an English word ");
break;
}
}
}
}
}
I recommend you first process the file and build a set of legal English words:
public static void main(String[] args) throws IOException {
Set<String> legalEnglishWords = new HashSet<String>();
Scanner file = new Scanner(new File("example.txt"));
while (file.hasNextLine()) {
String line = file.nextLine();
for (String word : line.split(" ")) {
legalEnglishWords.add(word);
}
}
file.close();
Next, get input from the user:
Scanner input = new Scanner(System.in);
System.out.println("Please enter in a message: ");
String message = input.nextLine();
input.close();
Finally, split the user's input to tokens and check each one if it is a legal word:
for (String userToken : message.split(" ")) {
if (legalEnglishWords.contains(userToken)) {
System.out.println(userToken + " is an English word ");
}
}
}
}
You may try with this. With this solution you can find each word entered by the user in your example.txt file:
public static void main(String[] args) throws IOException
{
String message = "";
String name = "";
Scanner input = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
System.out.println("Please enter in a message: ");
message = scan.nextLine();
Scanner file = new Scanner(new File("example.txt"));
while (file.hasNextLine())
{
String line = file.nextLine();
for (String word : message.split(" "))
{
if (line.contains(word))
{
System.out.println(word + " is an English word ");
}
}
}
}
As Mark pointed out in the comment, change
scan.next();
To:
scan.nextLine();
should work, i tried and works for me.
If you can use Java 8 and Streams API
public static void main(String[] args) throws Exception{ // You need to handle this exception
String message = "";
Scanner input = new Scanner(System.in);
System.out.println("Please enter in a message: ");
message = input.nextLine();
List<String> messageParts = Arrays.stream(message.split(" ")).collect(Collectors.toList());
BufferedReader reader = new BufferedReader(new FileReader("example.txt"));
reader.lines()
.filter( line -> !messageParts.contains(line))
.forEach(System.out::println);
}
You have many solution, but when it comes to find matches I suggest you to take a look to the Pattern and Matcher and use Regular Expression
I haven't fully understood your question, but you could do add something like this (I did not tested the code but the idea should work fine):
public static void main(String[] args) throws IOException{
String message = "";
String name = "";
Scanner input = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
System.out.println("Please enter in a message: ");
message = scan.next();
Scanner file = new Scanner(new File("example.txt"));
String pattern = "";
for(String word : input.split(" ")){
pattern += "(\\b" + word + "\\b)";
}
Pattern r = Pattern.compile(pattern);
while(file.hasNextLine())
{
String line = file.nextLine();
Matcher m = r.matcher(line);
if(m.matches()) {
System.out.println("Word found in: " + line);
}
}
}
I'm having a bit of trouble figuring out how to read multiple lines of user input into a scanner and then storing it into a single string.
What I have so far is down below:
public static String getUserString(Scanner keyboard) {
System.out.println("Enter Initial Text:");
String input = "";
String nextLine = keyboard.nextLine();
while(keyboard.hasNextLine()){
input += keyboard.nextLine
};
return input;
}
then the first three statements of the main method is:
Scanner scnr = new Scanner(System.in);
String userString = getUserString(scnr);
System.out.println("\nCurrent Text: " + userString );
My goal is to have it where once the user types their text, all they have to do is hit Enter twice for everything they've typed to be displayed back at them (following "Current text: "). Also I need to store the string in the variable userString in the main (I have to use this variable in other methods). Any help at all with this would be very much appreciated. It's for class, and we can't use arrays or Stringbuilder or anything much more complicated than a while loop and basic string methods.
Thanks!
Using BufferedReader:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = "";
String line;
while((line = br.readLine()) != null){
if(line.isEmpty()){
break; // if an input is empty, break
}
input += line + "\n";
}
br.close();
System.out.println(input);
Or using Scanner:
String input = "";
Scanner keyboard = new Scanner(System.in);
String line;
while (keyboard.hasNextLine()) {
line = keyboard.nextLine();
if (line.isEmpty()) {
break;
}
input += line + "\n";
}
System.out.println(input);
For both cases, Sample I/O:
Welcome to Stackoverflow
Hello My friend
Its over now
Welcome to Stackoverflow
Hello My friend
Its over now
Complete code
public static void main (String[] args) {
Scanner scnr = new Scanner(System.in);
String userString = getUserString(scnr);
System.out.println("\nCurrent Text: " + userString);
}
public static String getUserString(Scanner keyboard) {
System.out.println("Enter Initial Text: ");
String input = "";
String line;
while (keyboard.hasNextLine()) {
line = keyboard.nextLine();
if (line.isEmpty()) {
break;
}
input += line + "\n";
}
return input;
}
I am writing a program to change an input file. It should start a new line after a ? . and ! but I can't seem to figure it out. Each new line should also begin with an Uppercase letter which I think I got. It should also eliminate unnecessary spaces which I also believe I got.
For example: hello? bartender. can I have a drink!whiskey please.
Output should be:
Hello?
Bartender.
Can I have a drink!whiskey please.
It should only make a new line after those operators followed by a whitespace. If there is no space it will not make new line.
import java.util.Scanner;
import java.io.*;
public class TextFileProcessorDemo
{
public static void main(String[] args)
{
String fileName, answer;
Scanner keyboard = new Scanner(System.in);
System.out.println("Test Input File:");
fileName = keyboard.nextLine();
File file = new File(fileName);
PrintWriter outputStream = null;
try
{
outputStream = new PrintWriter(file);
}
catch(FileNotFoundException e)
{
System.out.println("Error opening file" + file);
System.exit(0);
}
System.out.println("Enter a line of text:");
String line = keyboard.nextLine();
outputStream.println(line);
outputStream.close();
System.out.println("This line was written to:" + " " + file);
System.out.println(" ");
TextFileProcessor.textFile();
}
}
Second Class
import java.io.*;
import java.util.Scanner;
public class TextFileProcessor
{
public static void textFile()
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Test Input File:");
String inputFile = keyboard.next();
System.out.print("Output File:");
String outputFile = keyboard.next();
try
{
BufferedReader inputStream = new BufferedReader(new FileReader(inputFile));
PrintWriter outputStream = new PrintWriter(new FileOutputStream(outputFile));
String line = inputStream.readLine();
line = line.replaceAll("\\s+", " ").trim();
line = line.substring(0,1).toUpperCase() + line.substring(1);
//This is where I would like to add code
while(line != null)
{
outputStream.println(line);
System.out.println(line);
line = inputStream.readLine();
}
inputStream.close();
outputStream.close();
}
catch(FileNotFoundException e)
{
System.out.println("File" + inputFile + " not found");
}
catch(IOException e)
{
System.out.println("Error reading from file" + inputFile);
}
}
}
A simple regex would suffice:
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
for(String s:"hello? bartender. can I have a drink!whiskey please.".replaceAll("(\\W)(\\s+)", "$1\n").split("\n"))
System.out.println(s.substring(0, 1).toUpperCase()+s.substring(1));
}
}
Output :
Hello?
Bartender.
Can I have a drink!whiskey please.
https://ideone.com/Zo2N7Q
Would this solve your problem?
if(line.endsWith("! ") || line.endsWith("? ") || line.endsWith(". ")) {
line = line + '\n';
}
You can use a "capture group" in a regex to achieve what you want.
line.replaceAll("(\\? )|(\\! )|(\\. )", "$0\n");
Update:
With regards to your comment on how to capitalize the first character of each line, you can use the toUpperCase method in the Character class.
line = Character.toUpperCase(line.charAt(0)) + line.substring(1);
Note:
If you are using Java 1.7 or above you should consider using a try-with-resources block for the Scanner
try (Scanner keyboard = new Scanner(System.in)) {
...
}
Then when you read input from the user you can manipulate it to the correct format before writing to your file. For example you could do something like...
System.out.println("Enter a line of text:");
String[] lines = keyboard.nextLine().replaceAll("(\\? )|(\\! )|(\\. )", "$0\n").split("\n");
// Replace the first character of each line with an uppercase character
for (int i = 0; i < lines.length; i++) {
lines[i] = Character.toUpperCase(lines[i].charAt(0)) + lines[i].substring(1);
}
Path path = Paths.get(fileName);
Files.write(path, Arrays.asList(lines), Charset.defaultCharset());
System.out.println("This line was written to:" + " " + path.toString());
System.out.println(" ");
As for reading and writing from files you are better off using the non-blocking Files class in the java.nio package. It's as simple as the following;
Path path = Paths.get(fileName);
Files.write(path, Arrays.asList(lines), Charset.defaultCharset());
Then for reading your file you can just use the readAllLines method.
List<String> lines = Files.readAllLines(path);
for (String line : lines ) {
System.out.println(line);
}
So I've got the basic code for this however due to the while loop I'm using, I can really only write the last line of the text file to the new file. I'm trying to modify the text from testfile.txt and write it to a new file named mdemarco.txt. The modification I'm trying to do is add a line number in front of each line. Does anybody know a way to maybe write the contents of the while loop to a string while it runs and output the resulting string to mdemarco.txt or anything like that?
public class Writefile
{
public static void main(String[] args) throws IOException
{
try
{
Scanner file = new Scanner(new File("testfile.txt"));
File output = new File("mdemarco.txt");
String s = "";
String b = "";
int n = 0;
while(file.hasNext())
{
s = file.nextLine();
n++;
System.out.println(n+". "+s);
b = (n+". "+s);
}//end while
PrintWriter printer = new PrintWriter(output);
printer.println(b);
printer.close();
}//end try
catch(FileNotFoundException fnfe)
{
System.out.println("Was not able to locate testfile.txt.");
}
}//end main
}//end class
The input file text is:
do
re
me
fa
so
la
te
do
And the output I'm getting is only
8. do
Can anybody help?
The String variable b is overwriten in each iteration of the loop. You want to append to it instead of overwriting (you may also want to add a newline character at the end):
b += (n + ". " + s + System.getProperty("line.separator"));
Better yet, use a StringBuilder to append the output:
StringBuilder b = new StringBuilder();
int n = 0;
while (file.hasNext()) {
s = file.nextLine();
n++;
System.out.println(n + ". " + s);
b.append(n).append(". ").append(s).append(System.getProperty("line.separator"));
}// end while
PrintWriter printer = new PrintWriter(output);
printer.println(b.toString());
Your content on each line of text didn't saved. So only the last line displays on the output file. Please try this:
public static void main(String[] args) throws IOException {
try {
Scanner file = new Scanner(new File("src/testfile.txt"));
File output = new File("src/mdemarco.txt");
String s = "";
String b = "";
int n = 0;
while (file.hasNext()) {
s = file.nextLine();
n++;
System.out.println(n + ". " + s);
//save your content here
b = b + "\n" + (n + ". " + s);
//end save your content
}// end while
PrintWriter printer = new PrintWriter(output);
printer.println(b);
printer.close();
}// end try
catch (FileNotFoundException fnfe) {
System.out.println("Was not able to locate testfile.txt.");
}
}// end m
Try this:
while(file.hasNextLine())
instead of:
while(file.hasNext())
and
b += (n+". "+s + "\n");
instead of:
b = (n+". "+s);
Change it to b += (n+". "+s);.
I need to write code that reads and does a text analysis of a file. One of the things it needs to do is to count how many words there are in the file. I wrote a method countWords, but when I run the program it returns 0. The text file I am using contains the following:
Ask not what your country can do for you
ask what you can do for your country
So it clearly should return 17 and not 0. What did I do wrong?
public class TextAnalysis {
public static void main (String [] args) throws IOException {
File in01 = new File("a5_testfiles/in01.txt");
Scanner fileScanner = new Scanner(in01);
System.out.println("TEXT FILE STATISTICS");
System.out.println("--------------------");
System.out.println("Length of the longest word: " + longestWord(fileScanner));
System.out.println("Number of words in file wordlist: " );
countWords(fileScanner);
}
public static String longestWord (Scanner s) {
String longest = "";
while (s.hasNext()) {
String word = s.next();
if (word.length() > longest.length()) {
longest = word;
}
}
return (longest.length() + " " + "(\"" + longest + "\")");
}
public static void countWords (Scanner s) throws IOException {
int count = 0;
while(s.hasNext()) {
String word = s.next();
count++;
}
System.out.println(count);
}
try this?
void countWords()
{
String temp;
File path = new File("c:/Bala/");//give ur path
File file = new File(path, "Bala.txt");//give ur filename
FileReader fr = new FileReader(file);
char cbuf[] = new char[(int) file.length()];
fr.read(cbuf);
temp = new String(cbuf);
String count[]=test.split("\\s");
System.out.println("Count:"+t.length);
}
You already read the scanner and reading it again. just create another scanner to use in count words method
fileScanner = new Scanner(<your file object>);
before
countWords(fileScanner);
Hope this helps.
Declare a new scanner for your count words method, the problem lies under s.next(); it reads the next word in your buffer and discard the previous ones, so after you called your longest word method, the scanner buffer has been used up.