sabi
12-08-2011, 07:07 AM
This program is about storing strings in an array from a file and then using selection sort to put them in ascending order. It is required to set the array to 100, but this file only have 5 names in it so the array is gonna be partially filled. The array is partially filled so i used a counter variable to hold the length of the filled arrayso i used counter in selection sort . When I try to run this program I get an error so can somebody take a look at it and help me fix it?
the .txt file that was used to fill the array contains these 5 names:
Thomas
Jordan
Alex
Ben
John
-----------------------------------------------------------------------
import java.util.Scanner;
import java.io.* ;
public class TestSort
{
public static void main(String[] args)throws IOException
{
int counter = 0;
String[] array = new String[100];
File inputFile = new File("input1.txt");
Scanner fileScanner = new Scanner(inputFile);
for(int i = 0; i < array.length; i++)
{
array[i] = fileScanner.nextLine();
counter++;
}
fileScanner.close();
// Apply selection sort to array
selectionSort(array, counter);
// Output contents of array in sorted order
for(int i = 0; i < counter; i++)
{
System.out.print("\"" + array[i] + "\" ");
}
}
static String[] selectionSort(String[] array, int counter)
{
for (int i = 1; i < counter; i++)
{
// find the index of the ith smallest value
int s = i-1;
for (int j = i; j < counter; j++)
{
if (array[j].compareTo(array[s]) < 0)
{
s = j;
}
}
// swap the ith smallest value into entry i-1
String temp = array[i-1];
array[i-1] = array[s];
array[s] = temp;
}
return array;
}
}
the .txt file that was used to fill the array contains these 5 names:
Thomas
Jordan
Alex
Ben
John
-----------------------------------------------------------------------
import java.util.Scanner;
import java.io.* ;
public class TestSort
{
public static void main(String[] args)throws IOException
{
int counter = 0;
String[] array = new String[100];
File inputFile = new File("input1.txt");
Scanner fileScanner = new Scanner(inputFile);
for(int i = 0; i < array.length; i++)
{
array[i] = fileScanner.nextLine();
counter++;
}
fileScanner.close();
// Apply selection sort to array
selectionSort(array, counter);
// Output contents of array in sorted order
for(int i = 0; i < counter; i++)
{
System.out.print("\"" + array[i] + "\" ");
}
}
static String[] selectionSort(String[] array, int counter)
{
for (int i = 1; i < counter; i++)
{
// find the index of the ith smallest value
int s = i-1;
for (int j = i; j < counter; j++)
{
if (array[j].compareTo(array[s]) < 0)
{
s = j;
}
}
// swap the ith smallest value into entry i-1
String temp = array[i-1];
array[i-1] = array[s];
array[s] = temp;
}
return array;
}
}