![]() |
![]() Fall Semester 2009 |
Here's a simplification of it (note the use of java.util.Arrays.toString()).
Also, here's how you print formatted output:
import java.util.*;
class One {
public static void main(String[] args) {
int[][] m = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
System.out.println(Arrays.deepToString(m));
for (int i = 0; i < m.length; i++) {
for (int j = 0; j < m[i].length; j++)
System.out.printf("%4d ", m[i][j]);
System.out.println();
}
}
}
Notes on sorting an array of objects: here (April 16, 2009). Code for a problem and its solution below:
Notes on writing your own sorting procedure (bubble sort, notes from 04/09/2009).import java.util.*; class Student implements Comparable{ double gpa; Student(double gpa) { this.gpa = gpa; } public String toString() { return "S(" + this.gpa + ")"; } public int compareTo(Student other) { if (this.gpa - other.gpa > 0) return 1; else if (this.gpa - other.gpa < 0) return -1; else return 0; // return (int) (this.gpa - other.gpa); does not work well! // 3.9 - 3.1 = 0.8 truncates to 0 instead of 1 and so on... } } class One { public static void main(String[] args) { ArrayList students = new ArrayList (); students.add(new Student(2.1)); students.add(new Student(3.9)); students.add(new Student(2.5)); students.add(new Student(1.1)); students.add(new Student(3.1)); students.add(new Student(1.9)); students.add(new Student(0.3)); System.out.println( students ); Collections.sort( students ); System.out.println( students ); } }