It vanishes.
It is possible to save run-time objects to disk. This is an advanced topic.
Here is an expanded MonthTester
that gives the user the option to save the data to a file as text.
If you have not yet looked at file I/O, skip this page.
An improvement to the program would ask the user for the filename. Another improvement would be to have the option to read in data from a file. Sounds like a great idea for a programming exercise.
public class MonthTester { public static void main( String[] args) throws IOException { Scanner scan = new Scanner( System.in ); Month jan = new Month( 1, 2017 ) ; String line = "Y"; // Fill Month with temperatures while ( line.toUpperCase().charAt(0) == 'Y' ) { System.out.print("day? "); int day = scan.nextInt(); System.out.print("temp ? "); int low = scan.nextInt(); if ( !jan.setTemp(day, low ) ) System.out.println("error in input"); System.out.print("Continue (Y/N)? "); line = scan.next(); } System.out.println( jan ); int validDays = jan.countValidDays(); if ( validDays > 0 ) { System.out.println( "Average Temperature: " + jan.avgTemp() ); } // Save Data to a File System.out.print("Save to file (Y/N)? "); line = scan.next(); if ( line.toUpperCase().charAt(0) == 'Y' ) { PrintWriter output = new PrintWriter( "monthData.txt" ); output.print( jan.toString() ) ; output.close(); } } }
The main()
method must include throws IOException
because creating a PrintWriter
might fail.
(Review: ) What might happen if you forget to close
the file?