...

View Full Version : I need help with storing strings in array in JAVA



sabi
12-08-2011, 08: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;
}
}

Fou-Lu
12-08-2011, 03:20 PM
The error would be nice. I'm assuming its throwing a NoSuchElementException off of the scanner though.
That is caused by this:


for(int i = 0; i < array.length; i++)
{

array[i] = fileScanner.nextLine();
counter++;

}

You have a fileScanner with a max of 5 elements, but are attempting to read 100 elements out of it. Switch that to:


int counter = 0;
while (fileScanner.hasNextLine())
{
array[counter++] = fileScanner.nextLine();
}

sabi
12-11-2011, 04:20 AM
The error is at,
// find the index of the smallest value

int s = i-1;
if (array[j].compareTo(array[s]) < 0)

Exception in thread "main" java.lang.NullPointerException

renegadeandy
12-11-2011, 04:30 AM
Ok so that means either the array[s] or array[j] element is not defined i.e if s = 4 and j = 5 either array element 4 doesnt exist i.e is Null, or array element 5 doesnt exist!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum