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

I need help with the FileReader and reading the integers from the .txt file into

ID: 3623458 • Letter: I

Question


I need help with the FileReader and reading the integers from the .txt file into the integer array. I believe the rest of my code is correct except for that part, but if anyone wants to look through it to make sure it would be greatly appreciated. I also need to make it work for strings, and I have no idea how to do that. That part isn't as important, only need to worry about that if your feeling really ambitious.



import java.util.*;
import java.io.*;


public class Lab5{

public static void main(String[] args) throws IOException
{
Scanner inFile = new Scanner(new FileReader("Integer.txt"));

while(inFile.hasNext())
{

int i = 0;
int[] list = inFile.next();
i++;
}
String sortedList = bubbleSort(list);
}
public void bubbleSort(int[] list)
{
boolean swapped;
do
{
swapped = false;
for(int i=1; i < list.length; i++)
{
if(list[i-1]>list[i])
{
int temp =list[i];
list[i] = list[i-1];
list[i-1] = temp;
swapped = true;
}
}


}while (swapped);
}


public int BinarySearch(int[] list, int value) {
int first = 0;
int last = list.length-1;
int mid = 0;

boolean found = false;
while (first <= last && !found)
{
mid = (first + last) / 2;
if (list[mid] == value)
found = true;
else if (list[mid] > value)
last = mid - 1;
else
first = mid + 1;
}
if (found)
return mid;
else
return -1;

}
}

Explanation / Answer

public static void main(String[] args) throws IOException
{
Scanner inFile = new Scanner(new FileReader("Integer.txt"));

// we don't know how many integers are in the file. We'll use an ArrayList for temporary storage
ArrayList<Integer> temp = new ArrayList<Integer>();

while(inFile.hasNextInt())
{
temp.add(inFile.nextInt());
}

// create array from list
int[] list = new int[temp.size()];
for(int i = 0; i < list.length; i++)
{
list[i] = temp.get(i);
}

// sort list
bubbleSort(list);

// print list
System.out.println(Arrays.toString(list));
}

We'll need to import java.util.*.