Create a program that prompts the user for survey responses and outputs each res
ID: 3660258 • Letter: C
Question
Create a program that prompts the user for survey responses and outputs each response to a file. Use and ofstream to create a file called "numbers.txt". Then create a program to read the survey responses from "numbers.txt" using an ifstream, input one at a time from the file. Program should read out responses until it reaches the end of the file.
Explanation / Answer
// Create poll results and output them to a file. import java.io.FileNotFoundException; import java.util.Formatter; import java.util.FormatterClosedException; import java.util.IllegalFormatException; import java.util.NoSuchElementException; import java.util.Scanner; public class CreateResults { private int getValue() { int result = -1; Scanner scanner = new Scanner( System.in ); // prompt the user for input System.out.print( "Enter integer result (1 - 10), -1 to quit: " ); try { result = scanner.nextInt(); } // end try catch ( NoSuchElementException noSuchElementException ) { System.err.println( "Error with input." ); System.exit( 1 ); } // end catch return result; } // end method getValue private void outputData() { Formatter pollNumbers = null; try { // create the output stream pollNumbers = new Formatter( "numbers.txt" ); 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 ) // write the value pollNumbers.format( "%d ", pollValue ); © 2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Student Solution Exercises pollValue = getValue(); // get another value } // end while pollNumbers.close(); // close the file } // end try catch( SecurityException securityException ) { System.err.println( "Error opening file." ); } // end catch catch( FileNotFoundException fileNotFoundException ) { System.err.println( "Output file cannot be found." ); } // end catch catch( IllegalFormatException illegalFormatException ) { System.err.println( "Error with the output's format." ); } // end catch catch( FormatterClosedException formatterClosedException ) { System.err.println( "File has been closed." ); } // end catch finally { if ( pollNumbers != null ) pollNumbers.close(); } // end finally } // end method outputData public static void main( String args[] ) { CreateResults application = new CreateResults(); application.outputData(); } // 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.