/* * Working with text files and arrays. The array is populated from a text file. * Use the Scanner class to read in the text file. Note the imports. * Allow NetBeans to assist you with the imports and the "try catch" statement. * * Here is what the text file looks like (months.txt). * The text file must be stored in the project folder (not the scr folder) * Jan * Feb * Mar * Apr * May * Jun * Jul * Aug * Sep * Oct * Dec */ package arrayrandomscanner6; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger; public class ArrayRandomScanner6 { // global private static variables for all methods in the class // Here we declare an empty String array into which we will read values private static String[] monthsArray = new String[12]; private static int counter = 0; public static void main(String[] args) { readTextFile(); displayArr(); } // ========================================================================= private static void readTextFile() { try { Scanner scFile = new Scanner(new File("months.txt")); while(scFile.hasNext()){ String line = scFile.nextLine(); monthsArray[counter] = line; counter++; } } catch (FileNotFoundException ex) { Logger.getLogger(ArrayRandomScanner6.class.getName()).log(Level.SEVERE, null, ex); } } // end method // ========================================================================== private static void displayArr() { System.out.println("Months from the text file"); System.out.println("========================="); for(int i = 0; i < counter;i++) { System.out.println(monthsArray[i]); } } // end method } // end class =========================================================================== OUTPUT Months from the text file ========================= Jan Feb Mar Apr May Jun Jul Aug Sep Oct Dec BUILD SUCCESSFUL (total time: 1 second)