Question: The second part of the exercise requires the first code to convert to a txt file instead of a dat file. Then I want the
The second part of the exercise requires the first code to convert to a txt file instead of a dat file. Then I want the second program to be able to read it and display
// Create poll results and output them to a file. import javax.swing.*; import java.io.*;
public class CreateResults {
private static int getValue() { // prompt the user for input String input = JOptionPane.showInputDialog( "Enter integer result (1 - 10), -1 to quit:" );
try { return Integer.parseInt( input ); // try to get an integer }
// if its not an integer catch( NumberFormatException format ) { return 11; // return an invalid value } }
public static void main( String args[] ) { try { // create the output stream DataOutputStream pollNumbers = new DataOutputStream( new FileOutputStream( "numbers.dat" ) );
int pollValue = getValue(); // get a number from the user
// test for the sentinel value while( pollValue != -1 ) {
// if the number is valid if ( pollValue > 0 && pollValue < 11 ) pollNumbers.writeInt( pollValue ); // write the value
pollValue = getValue(); // get another value }
pollNumbers.close(); // close the file }
catch( IOException ioException ) { JOptionPane.showMessageDialog( null, "Error with the file", "IOError", JOptionPane.ERROR_MESSAGE ); }
System.exit( 0 );
} // end main
} // end class CreateResults
Second code
// Read poll results from a file and output ratings. import javax.swing.*; import java.io.*;
public class StudentPoll {
public static void main( String args[] ) { int frequency[] = new int[ 11 ];
try { DataInputStream pollNumbers = new DataInputStream( new FileInputStream( "numbers.dat" ) );
try { // for each answer, use that value as subscript to // determine element to increment while( true ) ++frequency[ pollNumbers.readInt() ]; }
catch( EOFException eof ) { }
String output = "Rating\tFrequency ";
// append frequencies to String output for ( int rating = 1; rating < frequency.length; rating++ ) output += rating + "\t" + frequency[ rating ] + " ";
JTextArea outputArea = new JTextArea(); outputArea.setText( output );
PrintWriter writer = new PrintWriter( new FileWriter( "output.txt" ) ); writer.print( output ); writer.close();
JOptionPane.showMessageDialog( null, outputArea, "Student Poll Program", JOptionPane.INFORMATION_MESSAGE );
pollNumbers.close();
System.exit( 0 );
}
catch( IOException io ) { JOptionPane.showMessageDialog( null, "File Error", "IO Error", JOptionPane.ERROR_MESSAGE ); System.exit( 1 ); }
} // end main
} // end class StudentPoll
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
