Re: What is wrong with my program?
SamuelXiao,
Two SSCCEs, two code reviews, two rewrites.
I've learned a lot today. Thanks Lew. :)
import java.util.Arrays;
public class StudentFileReaderTest {
public static void main(String[] args) {
Integer[] students = new Integer[30];
Integer[] file =
{
// Don't fill the heap unnecessarily
Integer.valueOf(2),
Integer.valueOf(3),
Integer.valueOf(1),
Integer.valueOf(2),
Integer.valueOf(3)
};
int count = 0;
if ( file.length > 0 )
{
for ( int ix = 0;
// Watch your invariants
ix < file.length && count < students.length;
++ix )
{
// Don't perform unnecessary iterations
if( Arrays.binarySearch( students, 0, count, file [ix] ) < 0 )
{
students [count] = file[ix];
// Don't be unnecessarily verbose
Arrays.sort( students, 0, ++count );
}
}
}
for ( int ix = 0; ix < count; ++ix )
{
System.out.println( students [ix] );
}
}
}
Bo Vance started with this:
public class Scratch {
static Integer[] students = new Integer[30];
static int recordCount = 0;
public static void main(String[] args) {
Integer[] studentFile =
{
new Integer(2),
new Integer(3),
new Integer(1),
new Integer(2),
new Integer(3)
};
Arrays.fill(students, new Integer(-1));
for (Integer studentRecord : studentFile) {
addStudent(studentRecord);
}
recordCount = 0;
Integer test = students[recordCount];
while (test.intValue() < 0) {
recordCount++;
test = students[recordCount];
}
for (int i = recordCount; i < students.length; i++) {
System.out.println(students[i]);
}
}
static void addStudent(Integer student) {
if(Arrays.binarySearch(students, student) < 0) {
students[recordCount] = student;
recordCount++;
}
Arrays.sort(students);
}
}