Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I need help. I\'ve missed around with my program but i think i just made it wors

ID: 3627576 • Letter: I

Question

I need help. I've missed around with my program but i think i just made it worse.

(Student Poll) Figure 7.8 contains an array of survey responses that is hard coded into the program. Suppose we wish to process survey results that are stored in a file. This exercise requires two separate programs. First, create an application that prompts the user for survey responses and outputs each response to a file. Use a Formatter to create a file called numbers.txt. Each integer should be written using method format. Then modify the program of Fig. 7.8 to read the survey responses from numbers.txt. The responses should be read from the file by using a Scanner. Method nextInt should be used to input one integer at a time from the file. The program should continue to read responses until it reaches the end of file. The results should be output to the text file "output.txt".

import java.util.Scanner;
import java.io.*;
import java.io.File;
import java.util.Formatter;
import java.util.FormatterClosedException;
import java.util.IllegalFormatException;
import java.util.NoSuchElementException;

public class StudentPoll2
{
public void file()
{
String[] input;
PrintWriter outputFile;
boolean okToRead = false;
File outFile;
String lineOfText;
String response;
String fileInput, fileOutput;
Scanner keyboard = new Scanner(System.in);


//User enters the input file they wish to use
System.out.print("Enter the input file name: ");
fileInput = keyboard.nextLine();

System.out.println();

File inputFile = new File(fileInput);

//if statement checks to see if the file exists
if (inputFile.exists())
{
try
{
Scanner fileScanner = new Scanner(inputFile);
System.out.println("Enter the output file name: ");
fileOutput = keyboard.nextLine();

outFile = new File(fileOutput);

// if statement checks to see if the file exists
if (outFile.exists())
{
// if the file exists, the program will ask if the user would like to over write it
System.out.println("File exists." + " Do you want to overwrite the file? (Y/N)");
response = keyboard.nextLine();

if (response.equalsIgnoreCase("Y"))
{
okToRead = true;
}// end if
else
{
okToRead = false;
}// end else
}// end if
else
{
okToRead = true;
}// end else

if (okToRead)
{
PrintWriter dataWriter = new PrintWriter(outFile);

while (fileScanner.hasNext())
{
lineOfText = fileScanner.nextLine();
displayData();
}// end whie
fileScanner.close();
dataWriter.close();
}// end if
else
{
// if output file does not exist, program will terminate.
System.out.println("Program terminated.");
}// end else
}// end try
catch ( Exception ex )
{
System.err.println( "Error: Exception" );
} // end catch
}// end if
else
{
// if input file does not exist then an error message will be displayed
System.out.println("Error: The file " + fileInput + "does not exist.");
}// end else

}



displayData();

}// end method file

//
class displayData()
{
int[] frequency = new int[ 11 ];

Formatter writer = null;
Scanner pollNumbers = null;

try
{
pollNumbers = new Scanner(
new File( "numbers.txt" ) );

writer = new Formatter( "output.txt" );

writer.format( "%-12s%-12s ", "Rating", "Frequency" );

// for each answer, use that value as subscript to
// determine element to increment
while ( pollNumbers.hasNext() )
++frequency[ pollNumbers.nextInt() ];

// append frequencies to String output
for ( int rating = 1; rating < frequency.length; rating++ )
writer.format( "%-12d%-12d ", rating, frequency[ rating ] );
} // end try
catch ( Exception ex )
{
System.err.println( "Error: Exception" );
} // end catch

if ( writer != null )
writer.close();

if ( pollNumbers != null )
pollNumbers.close();

} // end displayData

public static void main( String[] args )
{
StudentPoll2 application = new StudentPoll2();
application.displayData();
} // end main

}// end class StudentPoll

Explanation / Answer

/* * StudentPoll2.java **/

import java.util.Scanner;
import java.io.*;
import java.io.File;
import java.util.Formatter;
import java.util.FormatterClosedException;
import java.util.IllegalFormatException;
import java.util.NoSuchElementException;


public class StudentPoll2 {
           
        boolean okToRead = false;
        File outFile;       
        String response;
        String fileInput, fileOutput;
        Scanner keyboard = new Scanner(System.in);   
   
    public StudentPoll2() {
       
        //User enters the input file they wish to use
        System.out.print("Enter the input file name: ");
        fileInput = keyboard.nextLine();               
        File inputFile = new File(fileInput);
       
        //if statement checks to see if the file exists
        if (inputFile.exists()) {
            try {
                Scanner fileScanner = new Scanner(inputFile);
                System.out.print("Enter the output file name: ");
                fileOutput = keyboard.nextLine();
               
                outFile = new File(fileOutput);
               
                // if statement checks to see if the file exists
                if (outFile.exists()) {
                // if the file exists, the program will ask if the user would like to over write it
                    System.out.println("File exists." + " Do you want to overwrite the file? (Y/N)");
                    response = keyboard.nextLine();
                   
                    if (response.equalsIgnoreCase("Y")) {
                        okToRead = true;
                    }// end if
                    else {
                        okToRead = false;
                    }// end else
                }// end if
                else {
                    okToRead = true;
                }// end else
               
                if (okToRead) {                  
                        displayData(fileScanner,outFile);
                   // }// end whie
                    fileScanner.close();                   
                }// end if
                else {
        // if output file does not exist, program will terminate.
                    System.out.println("Program terminated.");
                }// end else
            }// end try
            catch ( Exception ex ) {
                System.err.println( "Error: Exception" );
                ex.printStackTrace();
            } // end catch
        }// end if
        else {
        // if input file does not exist then an error message will be displayed
            System.out.println("Error: The file " + fileInput + "does not exist.");
        }// end else               
}// end method file

public void displayData(Scanner fileScanner,File outFile) {
   
    int[] frequency = new int[ 250 ];
    Formatter writer = null;
       
    try {       
        writer = new Formatter( outFile );       
        writer.format( "%-12s%-12s ", "Rating", "Frequency" );
       
        // for each answer, use that value as subscript to
        // determine element to increment
        while ( fileScanner.hasNext() )
            ++frequency[ fileScanner.nextInt() ];
       
        // append frequencies to String output
        for ( int rating = 1; rating < frequency.length; rating++ )
            writer.format( "%-12d%-12d ", rating, frequency[ rating ] );
    } // end try
    catch ( Exception ex ) {
        System.err.println( "Error: Exception" );
        ex.printStackTrace();
    } // end catch
   
    if ( writer != null )
        writer.close();
   
    if ( fileScanner != null )
        fileScanner.close();
   
} // end displayData

public static void main( String[] args ) {
    StudentPoll2 application = new StudentPoll2();   
} // end main

}// end class StudentPoll