please help me with part 3 I need to plug a txt file which I already have. Write
ID: 3935296 • Letter: P
Question
please help me with part 3
I need to plug a txt file which I already have.
Write a void method that takes a String as argument. This argument represents the name of a file containing some words, one per line. The method should have functionality to read the file which contains a word in each line, check whether or not the word is a palindrome and print to the screen all of the palindromes contained in the input file, one per line. Also, the last line of the output should have the message: "There are x palindromes out of y words in file words" (where x is the number of palindrome words in the input file, and y is the total number of words in the input file).Explanation / Answer
Hi,
Here is the program you have asked. The program used two integers to make the count of palindroms
1)Using this Scanner input = new Scanner(filename); the file you have submitted will be readed and the command next line will be used to read the first line of a file
2)for ( int i = length - 1; i >= 0; i-- ){
reverse = reverse + original.charAt(i);
} -----using this we will be checking the current string is palindrome or not if it si palindrom we will increate the count
import java.util.*;
import java.io.File;
import java.io.FileNotFoundException;
public class Exercise
{
public static void main(String args[])
{
int palindrome_cout=0,total_cout=0;
File filename = new File(args[0]);
try {
Scanner input = new Scanner(filename);
while (input.hasNext()) {
total_cout++;
String original, reverse = "";
original = input.nextLine();
int length = original.length();
for ( int i = length - 1; i >= 0; i-- ){
reverse = reverse + original.charAt(i);
}
if (original.equals(reverse)){
palindrome_cout++;
}
}
System.out.println("There are "+palindrome_cout+" out of "+ total_cout +" words in file words.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
If any doughts on any part of program please comment below on comments section thank you
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.