17.9 (Student Poll) Figure 7.8 contains an array of survey responses that is har
ID: 3647409 • Letter: 1
Question
17.9 (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".Explanation / Answer
// 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 CreateResultsRelated Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.