Question

In: Computer Science

Write a program that prompts the user to enter a file name, then opens the file...

Write a program that prompts the user to enter a file name, then opens the file in text mode and reads names. The file contains one name on each line. The program then compares each name with the name that is at the end of the file in a symmetrical position. For example if the file contains 10 names, the name #1 is compared with name #10, name #2 is compared with name #9, and so on. If you find matches you should print the name and the line numbers where the match was found.

While entering the file name, the program should allow the user to type quit to exit the program.

If the file with a given name does not exist, then display a message and allow the user to re-enter the file name.

The file may contain up to 100 names.

You can use an array or ArrayList object of your choosing, however you can only have one array or ArrayList.

Input validation:

a) If the file does not exist, then you should display a message "File 'somefile.txt' is not found." and allow the user to re-enter the file name.

b) If the file is empty, then display a message "File 'somefile.txt' is empty." and exit the program.

Hints:

a) Perform file name input validation immediately after the user entry and use a while loop .

b) Use one integer variable to count names in the file and another one for counting matches.

d) You can use either a while loop or a for loop to find the matches.

Solutions

Expert Solution

The code snippet in java with explanation is as below:

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class FileRead {

        public static void main(String[] args) throws IOException {
                // BufferedReader for taking user input
                BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
                String input = "";
                System.out.println("Enter File name or Quit to exit");          // Asking for user input
                input = br.readLine();
                while (!input.equalsIgnoreCase("quit")) {                                       
                        //asking for file names until user enters correct file name or enters quit
                        
                        List<String> records = new ArrayList<String>();                     //ArrayList to store values
                          try
                          {
                                  //taking filename with filepath i.e. F:/AB.txt
                            BufferedReader reader = new BufferedReader(new FileReader(input));
                            String line;
                            while ((line = reader.readLine()) != null)
                            {
                              records.add(line);                //reading names line by line and storing in arrayList
                            }
                            if(records.size()==0)               //check file size; if empty exit the program
                            {
                                System.out.println("File "+ input+" is empty");
                                break;
                            }
                            reader.close();
                                  int countMatch=0,totalRecords=records.size();

                            for(int i=0;i<records.size()/2;i++)
                                //checking first half of array with second half for match and traversing only half loop
                                  { 
                                          if(records.get(i).equalsIgnoreCase(records.get(records.size()-i-1)))
                                                  // check match symmetrically i.e. first with last element second with second last and so on
                                          {
                                                  countMatch++;                 
                                                  // increase count by 1everytime there is a match
                                                  System.out.println("Match found "+records.get(i)+" at line "+(i+1));          
                                                  //displaying line number and record when match
                                          }
                                  }
                            System.out.println("Total Number of matches found is "+countMatch);         // Printing the Count of Total matches of name
                            System.out.println("Total Number of Records in File is "+totalRecords);     // Printing total Number of records
                            input="quit";  //quitting program after the file is found and operation t=ran
                          }
                          
                          catch (FileNotFoundException e)
                          {
                        /* In case of file not found showing the User file is not found
                         * and asking h
                         */
                                  
                            System.out.println("File "+ input+" is not found");
                            System.out.println("Enter File name or Quit to exit");
                                input = br.readLine();
                            
                          }
                          catch (Exception e)
                          {
                                  System.err.format("Exception occurred trying to read '%s'.", input); //Error message for any errors
                                                          }
                          
                }//end of while
        }//end of main
}//end of class

Output

Code

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class FileRead {

   public static void main(String[] args) throws IOException {
       // BufferedReader for taking user input
       BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
       String input = "";
       System.out.println("Enter File name or Quit to exit");       // Asking for user input
       input = br.readLine();
       while (!input.equalsIgnoreCase("quit")) {                  
           //asking for file names until user enters correct file name or enters quit
          
           List<String> records = new ArrayList<String>();           //ArrayList to store values
           try
           {
               //taking filename with filepath i.e. F:/AB.txt
           BufferedReader reader = new BufferedReader(new FileReader(input));
           String line;
           while ((line = reader.readLine()) != null)
           {
           records.add(line);       //reading names line by line and storing in arrayList
           }
           if(records.size()==0)       //check file size; if empty exit the program
           {
               System.out.println("File "+ input+" is empty");
               break;
           }
           reader.close();
               int countMatch=0,totalRecords=records.size();

           for(int i=0;i<records.size()/2;i++)
               //checking first half of array with second half for match and traversing only half loop
               {
                   if(records.get(i).equalsIgnoreCase(records.get(records.size()-i-1)))
                       // check match symmetrically i.e. first with last element second with second last and so on
                   {
                       countMatch++;          
                       // increase count by 1everytime there is a match
                       System.out.println("Match found "+records.get(i)+" at line "+(i+1));      
                       //displaying line number and record when match
                   }
               }
           System.out.println("Total Number of matches found is "+countMatch);       // Printing the Count of Total matches of name
           System.out.println("Total Number of Records in File is "+totalRecords);   // Printing total Number of records
           input="quit"; //quitting program after the file is found and operation t=ran
           }
          
           catch (FileNotFoundException e)
           {
           /* In case of file not found showing the User file is not found
           * and asking h
           */
              
           System.out.println("File "+ input+" is not found");
           System.out.println("Enter File name or Quit to exit");
               input = br.readLine();
          
           }
           catch (Exception e)
           {
               System.err.format("Exception occurred trying to read '%s'.", input); //Error message for any errors
                           }
          
       }//end of while
   }//end of main
}//end of class


Related Solutions

Write a program that asks the user to enter the name of a file, and then...
Write a program that asks the user to enter the name of a file, and then asks the user to enter a character. The program should count and display the number of times that the specified character appears in the file. Use Notepad or another text editor to create a sample file that can be used to test the program. Sample Run java FileLetterCounter Enter file name: wc4↵ Enter character to count: 0↵ The character '0' appears in the file...
Write a program that prompts the user for a file name, make sure the file exists...
Write a program that prompts the user for a file name, make sure the file exists and if it does reads through the file, count the number of times each word appears and then output the word count in a sorted order from high to low. The program should: Display a message stating its goal Prompt the user to enter a file name Check that the file can be opened and if not ask the user to try again (hint:...
Write a JAVA program that prompts the user to enter a single name. Use a for...
Write a JAVA program that prompts the user to enter a single name. Use a for loop to determine if the name entered by the user contains at least 1 uppercase and 3 lowercase letters. If the name meets this policy, output that the name has been accepted. Otherwise, output that the name is invalid.
jgrasp environment, java write a complete program that prompts the user to enter their first name,...
jgrasp environment, java write a complete program that prompts the user to enter their first name, middle name, and last name (separately). print out thier name and initials, exactly as shown: your name is: John Paul Chavez your initials are: J. P. C. use string method chartAt() to extract the first (zero-th) character from a name(the name is a string type): username.charAt(0). thank you.
C++ Write a program that prompts for a file name and then reads the file to...
C++ Write a program that prompts for a file name and then reads the file to check for balanced curly braces, {; parentheses, (); and square brackets, []. Use a stack to store the most recent unmatched left symbol. The program should ignore any character that is not a parenthesis, curly brace, or square bracket. Note that proper nesting is required. For instance, [a(b]c) is invalid. Display the line number the error occurred on. These are a few of the...
Write a program that prompts the user to enter a positive integer and then computes the...
Write a program that prompts the user to enter a positive integer and then computes the equivalent binary number and outputs it. The program should consist of 3 files. dec2bin.c that has function dec2bin() implementation to return char array corresponding to binary number. dec2bin.h header file that has function prototype for dec2bin() function dec2binconv.c file with main function that calls dec2bin and print results. This is what i have so far. Im doing this in unix. All the files compiled...
Problem 4 : Write a program that prompts the user to enter in an integer and...
Problem 4 : Write a program that prompts the user to enter in an integer and then prints as shown in the example below Enter an integer 5 // User enters 5 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 Bye
IN C++ Write a program that prompts the user to enter the number of students and...
IN C++ Write a program that prompts the user to enter the number of students and each student’s name and score, and finally displays the student with the highest score (display the student’s name and score). Also calculate the average score and indicate by how much the highest score differs from the average. Use a while loop. Sample Output Please enter the number of students: 4 Enter the student name: Ben Simmons Enter the score: 70 Enter the student name:...
1. Write a program that prompts the user for a filename, then reads that file in...
1. Write a program that prompts the user for a filename, then reads that file in and displays the contents backwards, line by line, and character-by character on each line. You can do this with scalars, but an array is much easier to work with. If the original file is: abcdef ghijkl the output will be: lkjihg fedcba Need Help with this be done in only PERL. Please use "reverse"
Create a program that when run, prompts the user to enter a city name, a date,...
Create a program that when run, prompts the user to enter a city name, a date, the minimum temperature and the maximum temperature. Calculate the difference between the maximum temperature and the minimum temperature. Calculate the average temperature based on the minimum and maximum temperature. Print out the following: City name today's Date minimum temperature maximum temperature average temperature difference between minimum and maximum The following is a sample run, user input is shown in bold underline. Enter City Name:...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT