Hello. I am slowly but (somewhat) surely trying to learn
Java. My currnet task is to read the information for an array from a file, print the array, and then sort and display the smallest element. My program lacks the method/code to print the entire element because I am having bigger issues. My program keeps telling me that the smallest value is 0 when it should be 3. Can anyone tell me where I am going wrong?
The file contains:
5 (number of elements, right?)
25
15
3
7
31
My code so far is:
/* File: Find_Smallest_Elements.java
* Author: Christina Wilson
* Date: 05-01-2005
* Purpose: Sorts for and displays smallest value
* in an array.
*/
import java.io.*;
public class Find_Smallest_Elements {
//method to sort array and find smallest elements
public static void findSmallest(int[] array) {
for (int i = 0; i < (array.length-1); i++) {
//position of smallest element
int min = i;
//for loop to locate smallest element
for (int j = i; j < (array.length); j++) {
if (array[j] < array[min])
min = j;
}// end for
//moves elements so that they are eventually
//arranged in order from smallest to largest
int temp = array[min];
array[min] = array[i];
array[i] = temp;
} // end for
} // end method
//main method to load array from file
//and to request smallest element
public static void main(
String[] args) throws IOException {
int[] array;
int items = 0;
int value = 0;
try {
BufferedReader br = new BufferedReader (
new FileReader("integers.dat"));
items = Integer.parseInt(br.readLine());
array = new int[items];
for (int i = 0; i < array.length; i++) {
value = Integer.parseInt(br.readLine());
array = new int[value];
}
br.close();
// Call the method to sort the array.
findSmallest(array);
// Print the array.
System.out.println("The smallest value is " + array[0]);
} catch (IOException ioe) {
System.out.println("Error in IO");
System.out.println("Message is:" + ioe.getMessage());
}
} // end method
} // end class
Help, please!
Thanks
Christy