Iterating though a text file in Java so that each line has information about that line


Iterating though a text file in Java so that each line has information about that line



Ok, so I really didn't know how to say it right for the title so this should shed some light on the situation.



I'm making a palindrome program in Java. In every which way you look at it, it works just fine. It reads in a file using Scanner, searches through the entire file and outputs if that line in the text file is a palindrome. If you have any special characters or caps it deletes them and turns everything to lowercase.


Scanner



My issue is that after the check is done on each line, I want to show some extra information next to the result.



Each line should show how many words are in the line, how many characters and if its a palindrome or not.



Anyway here is the code, hopefully someone can help me figure this out. Thanks.


import java.io.File;
import java.util.Scanner;

public class Palindrome {

public static void main(String args) {
//Global Variables
Scanner cScan = null;
Scanner wScan = null;
Scanner pScan = null;
int charCount = 0, numLines = 0, numChars = 0, wordCount = 0;

//Take in User Input
Scanner iScan = new Scanner(System.in); //Start input Scanner
String fileName = null;

System.out.print("Please Enter a File Name: ");
fileName = iScan.nextLine();

iScan.close(); //Close input Scanner

//Read File Specified by User
File palin = new File(fileName);

try {

//Checks for Number of Characters
cScan = new Scanner(palin);

while(cScan.hasNextLine()) {

String line = cScan.nextLine();

numChars += line.length();
numLines++;
}

//Checks for Number of Words
wScan = new Scanner(palin);

while (wScan.hasNext()) {

wScan.next();
wordCount++;
}

//Format Lines
pScan = new Scanner(palin);

while (pScan.hasNext()) {

String line = pScan.nextLine();
String reString = line.replaceAll("[^\p{L}\p{Nd}]", "");
String lString = reString.toLowerCase();
boolean pali = false;
String tP = "Yes", fP = "No";

int n = lString.length();

for (int i = 0; i < (n / 2) + 1; ++i) {
if (lString.charAt(i) != lString.charAt(n - i - 1)) {
pali = false;
break;
}
else if (lString.charAt(i) == lString.charAt(n - i - 1)) {
pali = true;
break;
}
}

if (pali == true)
System.out.println(line + " w: " + wordCount + ", " + " c: " + charCount + ", " + tP);
else
System.out.println(line + " w: " + wordCount + ", " + " c: " + charCount + ", " + fP);
}

}
catch(Exception e) {
System.out.println("File Could Not be Found");
}

//charCount = (numLines + numChars) - 1; //Minus 1 to Compensate for EOL at EOF
//System.out.println(charCount);
//System.out.println(wordCount);
//System.out.println(spRemover);
}
}





What's bothering you?
– Sotirios Delimanolis
Sep 12 '13 at 21:26





"I want to show some extra information next to the result." -- What extra information? Have you tried to do this in the code above? Does it not work or cause error?
– Hovercraft Full Of Eels
Sep 12 '13 at 21:28


"I want to show some extra information next to the result."





In case you don't know: There is System.out.print() method that continues output to the current line (does not start with the new line). So you can use this method instead of concatenating the entire line before printing.
– PM 77-1
Sep 12 '13 at 21:36


System.out.print()





To know the total characters, you can use the length() method, before that you can use a replaceAll() method if you want to delete any blank space (or special character). To know the total of words, you can use the split() method with a blank space as delimiter. To know if the word is a palindrome.... you already have that functionality do you?
– n3k0
Sep 12 '13 at 21:38





Are you sure this code works fine? You have a break statement under "pali = true;". The moment you have your first and last character matching you are calling the line a palindrome without checking the subsequent characters. And your else if block is potentially the same as else block.
– SerotoninChase
Sep 12 '13 at 21:41





2 Answers
2



I cleaned up your code a little bit.


import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Palindrome {

int charCount = 0;
int totalWordCount = 0;

public static String isPalindrome(String str) {
if(str.equals(new StringBuffer().append(str).reverse().toString())) {
return "a";
}
else {
return "not a";
}
}

public static int getNumberOfWords(String str) {
return str.isEmpty() ? 0 : str.split("\s+").length;
}

public void process(File file) {
try {
Scanner sc = new Scanner(file);
int i = 0;
while(sc.hasNextLine()) {
i++;
String line = sc.nextLine();
int wordCount = getNumberOfWords(line);
System.out.println("Line " + i + "is " + isPalindrome(line) + " palindrome. It has " + wordCount + " words and " + line.length() + " characters.");
charCount = charCount + line.length();
totalWordCount = totalWordCount + wordCount;
}
sc.close();
System.out.println("There are " + i + " lines in the file with a total of " + totalWordCount + " words and " + charCount + " characters.");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}

public static void main(String args) {
Scanner iScan = new Scanner(System.in);
String fileName = null;

System.out.print("Please Enter a File Name: ");
fileName = iScan.nextLine();

iScan.close();

File file = new File(fileName);
Palindrome pal = new Palindrome();
pal.process(file);
}
}


import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;

public class IteratingFileWithInformation {

int charCount = 0 ;
int totalWordCount = 0;

private static String checkPalindrome(String line) {

return line.equals(new StringBuffer().append(line).reverse().toString()) ? "a" : "not a" ;

}

private static int getNumberOfWords(String words) {
return words.isEmpty() ? 0 : words.split("\s+").length;
}

private void checkFileAndProcess(BufferedReader file) {

Scanner input = new Scanner(file);
int i = 0;
while(input.hasNextLine()) {
i++;
String line = input.nextLine();
int wordCount = getNumberOfWords(line);
System.out.println("Line: " + i + " is " + checkPalindrome(line) + " Palindrome. It has " + wordCount + " words and " + line.length() +
" characters. ");
charCount += line.length();
totalWordCount += wordCount;
}
input.close();
System.out.println("There are " + i + " lines in the file with a total of " + totalWordCount + " words and " + charCount + " characters.");
}

public static void main(String args) throws FileNotFoundException {

Scanner givefileName = new Scanner(System.in);
String fileName = null;
System.out.println("Enter the file name :");
fileName = givefileName.nextLine();
givefileName.close();

FileReader file = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(file);
IteratingFileWithInformation fileWithInformation = new IteratingFileWithInformation();
fileWithInformation.checkFileAndProcess(bufferedReader);
}
}






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Boo (programming language)

How to make file upload 'Required' in Contact Form 7?