Question

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

JAVA

Write a program that prompts the user to enter a file name, then opens the file in text mode and reads it. The input files are assumed to be in CSV format. The input files contain a list of integers on each line separated by commas. The program should read each line, sort the numbers and print the comma separated list of integers on the console. Each sorted list of integers from the same line should be printed together on a separate line on the console (see below for test cases).

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.

On each line the input file may contain any number of integers.

You can use any number of stacks, queues, arrays, or ArrayList objects in your program.

You may choose to use any of the sorting algorithms (provided in above class files for your convenience). All classes are uploaded in advance and there is no need to upload them with your submission. You should only upload one file: FileSorting.java. You are able to download the sorting algorithms in their respective files to use in your eclipse project for testing.

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) You can use either StringTokenizer class or String.split() method to separate each line into tokens.

c) For each line, create an array of integers and populate with the numbers from that line.

d) Use either one of the InsertionSort.sort(), SelectionSort.sort(), or BubbleSort.sort() methods to sort the integers.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

I was not sure if user is entering a '.txt' file or a '.csv' file so i wrote the code on the basis that user enters the extension with the file name. If you know the extension and does not want the user to enter the extension in the input then you can update the code and uncomment the line csvFile = csvFile + ".csv"; if the extension is '.csv' otherwise uncomment the line csvFile = csvFile + ".txt"; if the extension is '.txt' just below the 'try{' statement.

import java.io.BufferedReader;

import java.io.File;

import java.io.FileReader;

import java.io.IOException;

import java.util.Scanner;

public class FileSorting

{

    public static int fun()

    {

        //creating object of Scanner

        final Scanner s=new Scanner(System.in);

        System.out.print("Enter file name:");

        //taking file name input

        String csvFile = s.nextLine();

        //checking if user entered quit

        if(csvFile.equals("quit")||csvFile.equals("Quit")||csvFile.equals("QUIT"))

        {

            //returning -1 if user entered quit

            return -1;

        }

        else

        {

            try {

            //csvFile = csvFile + ".csv";    

            //csvFile = csvFile + ".txt";    

            //creating object of file

            final File file = new File(csvFile);

            //checking if file exists and if file is not empty

            if(file.exists()&&file.length()!=0)

            {

                final FileReader fr = new FileReader(file);

                final BufferedReader br = new BufferedReader(fr);

                String line = "";

                //creating a string array

                String[] tempArr;

                //reading the input line by line and spliting when ',' arise

                //and storing each element in tempArr

                while((line = br.readLine()) != null) {

                    tempArr = line.split(",");

                    //calculating the length of each row

                    final int len=tempArr.length;

                    //defining a int array

                    final int arr[]=new int[len];

                    //converting string array to int array

                    for(int i=0;i<len;i++)

                    arr[i]=Integer.parseInt(tempArr[i]);

                    //applying insertion sort on arr

                    for (int j = 1; j < len; j++) {  

                        final int key = arr[j];  

                        int i = j-1;  

                        while ( (i > -1) && ( arr[i] > key ) ) {  

                            arr[i+1] = arr[i];  

                            i--;  

                        }  

                        arr[i+1] = key;  

                    }

                    //displaying the output after sorting

                    for(int i=0;i<len;i++)

                    System.out.print(arr[i]+",");

                    System.out.println();

                }

                br.close();

            }

            //checking if file exists but is empty

            else if(file.length()==0&&file.exists())

            {

                System.out.println("File "+file+" is empty");

                return 0;

            }

            //when file is not found

            else

            {

                System.out.println("File "+file+" not found");

                return 0;

            }

        }

        catch(final IOException ioe) {

            ioe.printStackTrace();

        }

    }

        return 0;

    }

    public static void main(final String args[])

    {

        int a;

        //calling the function fun until the user enters quit

        do

        {

            a=fun();

        }while(a!=-1); //if user enters quit we return -1 from fun()

        //if we get a=-1 it means user entered quit

        if(a==-1)

        System.out.println("You entered quit");

    }

}

Output:

File Edit Selection View Go Run Terminal Help file.csv - java - Visual Studio Code Х FileSorting.java 3 file.csv X C:4 CommanIn the above pic you can see the content of 'file.csv' and the output after running the code. There was no file named 'abc.csv' so the output was 'File abc.csv was not found'.

Add a comment
Know the answer?
Add Answer to:
JAVA Write a program that prompts the user to enter a file name, then opens the...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • write a python program that prompts the user for a name of a text file, opens...

    write a python program that prompts the user for a name of a text file, opens that file for reading , and tracks the unique words in a file and counts how many times they occur in the file. Your program should output the unique words and how often they occur in alphabetical order. Negative testing for a file that does not exist and an empty file should be implemented.

  • The name of the C++ file must be search.cpp Write a program that will read data...

    The name of the C++ file must be search.cpp Write a program that will read data from a file. The program will allow the user to specify the filename. Use a loop that will check if the file is opened correctly, otherwise display an error message and allow the user to re-enter a filename until successful. Read the values from the file and store into an integer array. The program should then prompt the user for an integer which will...

  • Finish the given ProcessFile.java program that prompts the user for a filename and reprompts if file...

    Finish the given ProcessFile.java program that prompts the user for a filename and reprompts if file doesn’t exist. You will process through the file skipping any text or real (double) numbers. You will print the max, min, sum, count, and average of the integers in the file. You will want to create test files that contain integers, doubles, and Strings. HINT: Use hasNextInt() method and while loop. You may also want to use Integer.MAX_VALUE and Integer.MIN_VALUE for the initialization of...

  • Finish FormatJavaProgram.java that prompts the user for a file name and assumes that the file contains...

    Finish FormatJavaProgram.java that prompts the user for a file name and assumes that the file contains a Java program. Your program should read the file (e.g., InputFile.java) and output its contents properly indented to ProgramName_Formatted.java (e.g., InputFile_Formatted.java). (Note: It will be up to the user to change the name appropriately for compilation later.) When you see a left-brace character ({) in the file, increase your indentation level by NUM_SPACES spaces. When you see a right-brace character (}), decrease your indentation...

  • Write a complete Python program with prompts for the user for the main text file (checks...

    Write a complete Python program with prompts for the user for the main text file (checks that it exists, and if not, output an error message and stop), for any possible flags (including none), and for any other input that this program may need from the user: split has an option of naming the smaller files head_tail list the first 10 lines (default) and the last 10 lines (default) in order of the given text file flag: -# output #...

  • Java program Program: Grade Stats In this program you will create a utility to calculate and...

    Java program Program: Grade Stats In this program you will create a utility to calculate and display various statistics about the grades of a class. In particular, you will read a CSV file (comma separated value) that stores the grades for a class, and then print out various statistics, either for the whole class, individual assignments, or individual students Things you will learn Robustly parsing simple text files Defining your own objects and using them in a program Handling multiple...

  • Homework IX-a Write a program that opens a text file, whose name you enter at the keyboard You wi...

    Homework IX-a Write a program that opens a text file, whose name you enter at the keyboard You will be using the file text.txt to test your program. Print out all of the individual, unique words contained in the file, in alphabetical order Print out the number of unique words appearing in text.txt. Call your program: YourName-HwrklXa.py Make sure that your name appears as a comment at the beginning of the program as well as on the output display showing...

  • Please write this in C. Write this code in Visual Studio and upload your Source.cpp file for checking (1) Write a program to prompt the user for an output file name and 2 input file names. The progra...

    Please write this in C. Write this code in Visual Studio and upload your Source.cpp file for checking (1) Write a program to prompt the user for an output file name and 2 input file names. The program should check for errors in opening the files, and print the name of any file which has an error, and exit if an error occurs opening any of the 3 For example, (user input shown in caps in first line) Enter first...

  • PLEASE complete this in java. Write a program that prompts the user to enter a file...

    PLEASE complete this in java. Write a program that prompts the user to enter a file name and displays the occurrences of each letter in the console window and in a file. Letters are case insensitive. Use “USAconst.txt” for input and “letterCount.txt” for output. Use try- catch blocks to handle checked exceptions. Here is a sample file output: is ወ The ወ ው The Enter file name: USAconst.txt The occurrence of A's is 2675 The occurrence of B's is 612...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT