Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

name it ArrayDemo.java Create a program that will open a file named numbers.txt.

ID: 3808416 • Letter: N

Question

name it ArrayDemo.java

Create a program that will open a file named numbers.txt. This will be a file that will contain one integer number on each line.

Create a 100 element array. After opening the file, your program will read each number from the file and store the numb ers into the array. The integers in the file can be any valid

integer including positive numbers, negative numbers, and zero. After storing all the numbers into the array, create a loop that will cycle through the array and printout

the numbers to the screen, one number per line (use the System.out.println method). Your loop is to loop only enough times to printout the numbers read into the array.

You will not know how many numbers are in the file, so you need to code your program to work with files that may contain any number of numbers.

Explanation / Answer

numbers.txt (Save this file under D Drive.Then the path of the file pointing to it is D: umbers.txt )

34
-23
44
55
66
77
-98
76
65
-56
-78
-12
-43
-54
-65
12
99
18
82
99
11
22
33

_________________

ArrayDemo.java

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ArrayDemo {

   public static void main(String[] args) {
       //Declaring variables
       int count=0;
      
       //Creating an integer Array of size 100
       int numArray[]=new int[100];
         
       //Creating the Scanner class reference
       Scanner sc =null;
      
       /* Opening the file and reading the numbers from
       * the file and populating them into an array
       * */
       try {
           //Opening the file
           sc = new Scanner(new File("D: umber123.txt"));
              
           /* This while loop continues to execute until
           * it reads all the numbers from the file
           */
               while(sc.hasNextInt())
               {
                   //Populating elements into an array
                   numArray[count]=sc.nextInt();
               count++;
               }
           } catch (FileNotFoundException e) {
               System.out.println("Exception :"+e);
           }
       sc.close();
         
       //Displaying the elements from the Array
       System.out.println("Displaying the elements in the Array :");
       for(int i=0;i<count;i++)
       {
           System.out.println(numArray[i]);
       }
         
         

   }

}

______________________

Output:

Displaying the elements in the Array :
34
-23
44
55
66
77
-98
76
65
-56
-78
-12
-43
-54
-65
12
99
18
82
99
11
22
33

______________Thank You