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

Java im trying to get the output into an array(the size will vary) so I can perf

ID: 3696695 • Letter: J

Question

Java

im trying to get the output into an array(the size will vary) so I can perform a binary search. How would I get the output into an array without importing java.util.arrays?(Note. I am a beginner.)

public static void main(String[] args)

   {

       try

       {

       File f = new File("file.txt");

       Scanner input = new Scanner(f);

       String s = "";

       int total = 0;

      

       while(input.hasNextLine())

       {

           s = input.nextLine();

           total = Integer.parseInt("" + s);

           System.out.print(total + " ");

       }

           //System.out.println(total);

       }

      

      

      

      

       catch(Exception e)

       {

           System.out.println("File not found.");

       }

The Code output:

2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

And the file looks something like this:

2

3

5

7

11

13

17

19

23

29

31

37

41

43

47

53

59

61

67

71

73

79

83

89

97

Explanation / Answer

Hi, I have modified the code in such a way that we can store integers from file to arrays. Highlighted areas are the code changes.

AssignArray.java


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

public class AssignArray {

   /**
   * @param args
   */
   public static void main(String[] args) {
       // TODO Auto-generated method stub
       try
   {
   File f = new File("D:\file.txt");
   Scanner input1 = new Scanner(f);
   Scanner input2 = new Scanner(f);
   String s = "";
   int total = 0;

/*indicates number of lines in a file*/
   int lineCount = 0;

/*Finding how many number of records in file*/
   while(input2.hasNextLine()){
       input2.nextLine();
       lineCount++;
   }

/*creating array with length by using lineCount variable*/
   int arr[] = new int[lineCount];
   int i = 0;

   while(input1.hasNextLine())
   {
   s = input1.nextLine();

/*assigning values to array*/
   arr[i] = Integer.parseInt(s);
   i++;

   total = Integer.parseInt("" + s);
   System.out.print(total + " ");
   }
   System.out.println(" --------Array Elements----------");
   for(int j=0 ; j<arr.length; j++){
       System.out.print(arr[j]+" ");
   }

   }
  
  
  
  
   catch(Exception e)
   {
   System.out.println("File not found.");
   }
   }

}

Output:


2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
--------Array Elements----------
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote