How do I count multiple duplicate elements in an ArrayList? - java

I have a program that takes in a file list of bands and albums. I need to determine the number of album each band makes and then print out a list of the the bands and the number of albums they made in descending order. I have looked around and seen it done using mapping and collections. I want to know how to do it without either. Here is what I have so far:
public static void processFile(String filename)
{
String bandname = "";
String[][] data = read_spreadsheet(filename);
//takes the file and converts it to a 2d array
ArrayList<String> bands = new ArrayList<String>();
for(int rows = 0; rows < data.length; rows++)
{
bands.add(data[rows][0]);
}
for(int i = 0; i<bands.size()-1;i++)
{
int albumcount = 0;
for(int j = i+1; j<bands.size();j++)
{
if(bands.get(i).equals(bands.get(j)))
{
albumcount++;
}
}
}
}
input example:
band1 -album
band2 -album
band1 -album
band3 -album
band1 -album
band2 -album
output example:
band1: 3
band2: 2
band3: 1

Without collections? You want to use arrays?
String [] names = new String[data.length];
int [] counts = new int[data.length];
int j = 0;
for (int i = 0; i < data.lenght; i++ ) {
while (j < data.length) {
if (data[i][0].equals(names[j])) {
found = true;
counts[j]++;
break;
} else if (names[j] == null) {
names[j] = data[i][0];
counts[j]=1;
break;
}
j++;
}
}
// find max count
// println
// nullify element
// repeat
for (int i = 0; i < j; i++) {
int max = -1;
int k = i;
int pos = -1;
while ( k < j ) {
if ( counts[k] > max ) {
pos = k;
max = counts[k];
}
k++;
}
if ( pos != -1 ) { // we found
System.out.println ( names[pos] + ": " + counts[pos]);
counts[pos] = -1;
}
}

If you sort the list of band names (with duplicates) and then count how many of each band name is in the list, you will get the album count for each band:
public static void processFile(String filename)
{
//takes the file and converts it to a 2d array
String[][] data = read_spreadsheet(filename);
// get all the bands (with duplicates)
ArrayList<String> bands = new ArrayList<String>();
for(int rows = 0; rows < data.length; rows++) {
bands.add(data[rows][0]);
}
// sort the bands alphabetically
Collections.sort(bands);
int albumCount = 1;
String currentBand = bands.remove(0);
while(bands.size() > 0) {
String nextBand = bands.remove(0);
if(currentBand.equals(nextBand)) {
albumCount++;
} else {
// print the current band album count and setup for the next band
System.out.println(currentBand + ": " + albumCount);
currentBand = nextBand;
albumCount = 1;
}
};
// print the final band album count
System.out.println(currentBand + ": " + albumCount);
}

Related

How do I get rid of java.lang.NumberFormatException error

This code takes two txt files, reads them puts them in 2d arrays and should check if the numbers in the files are magic squares but it keeps returning NumberFormatException error. I'm new to java so if anyone could help me that would be great. I'm pretty sure the problem come from the txt file being string and the 2d array needing to be in int form. But how and where do I make that conversion on my code?
this is what i have:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
public class ms {
public static void main(String[] args) throws FileNotFoundException {
String filename1 = "magicSquaresData.txt", filename2 = "magicSquaresData.txt";
int nos[][] = null;
nos = getArray(filename1);
boolean b = isMagicSquare(nos);
printArray(nos);
if (b) {
System.out.println("It is a magic Square");
} else {
System.out.println("It is not a magic Square");
}
System.out.println("\n");
nos = getArray(filename2);
b = isMagicSquare(nos);
printArray(nos);
if (b) {
System.out.println("It is a magic Square");
} else {
System.out.println("It is not a magic Square");
}
}
private static int[][] getArray(String filename) throws FileNotFoundException {
String line;
int nos[][] = null;
int size = 0, rows = 0;
Scanner sc = null;
try {
sc = new Scanner(new File(filename));
while (sc.hasNext()) {
if (!sc.nextLine().isEmpty())
size++;
}
sc.close();
nos = new int[size][size];
sc = new Scanner(new File(filename));
while (sc.hasNext()) {
line = sc.nextLine();
if (!line.isEmpty()) {
String arr[] = line.split("\t");
for (int i = 0; i < arr.length; i++) {
nos[rows][i] = Integer.valueOf(arr[i]);
}
rows++;
}
}
sc.close();
} catch (FileNotFoundException e) {
System.out.println(e);
}
return nos;
}
private static void printArray(int[][] nos){
for(int i = 0; i<nos[0].length;i++) {
for (int j = 0; j < nos[0].length; j++){
System.out.printf("%-3d",nos[i][j]);
}
System.out.println();
}
}
private static boolean isMagicSquare(int[][] square) {
boolean bool = true;
int order = square.length;
int[] sumRow = new int[order];
int[] sumCol = new int[order];
int[] sumDiag = new int[2];
Arrays.fill(sumRow, 0);
Arrays.fill(sumCol, 0);
Arrays.fill(sumDiag, 0);
for (int row = 0; row < order; row++){
for (int col = 0; col < order; col++) {
sumRow[row] += square[row][col];
}
}
for (int col = 0; col < order; col++) {
for (int row = 0; row < order; row++) {
sumCol[col] += square[row][col];
}
}
for (int row = 0; row < order; row++) {
sumDiag[0] += square[row][row];
}
for (int row = 0; row < order; row++) {
sumDiag[1] += square[row][order - 1 - row];
}
bool = true;
int sum = sumRow[0];
for (int i = 1; i < order; i++) {
bool = bool && (sum == sumRow[i]);
}
for (int i = 0; i < order; i++) {
bool = bool && (sum == sumCol[i]);
}
for (int i = 0; i < 2; i++) {
bool = bool && (sum == sumDiag[i]);
}
return bool;
}
}
SUGGESTION:
Substitute nos[rows][i] = Integer.valueOf(arr[i]); for a custom method that will tell you WHERE the error is occurring.
EXAMPLE:
public static Integer tryParse(String text, int row, int i) {
try {
return Integer.parseInt(text);
} catch (NumberFormatException e) {
System.out.println("ERROR: row=" + row + ", i=" + i + ", text=" + text);
return null;
}
}
CAVEAT: This is for helping you troubleshoot ONLY. You definitely wouldn't want to release this in "production code" ;)
What is the NumberFormatException?
Thrown to indicate that the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format.
Offtopic:
A thing that i can notice is that both filesnames have the same name. So you will verify the same file 2 times.
String filename1 = "magicSquaresData.txt", filename2 = "magicSquaresData.txt";
I checked your program and you error appears when you put like this on a file:
1. 5 5
2. 5 5
So the error shows beacause you are trying to parse to int the String "5 5". So your code pick the all line and tries to convert to int and " " it's not an int. And there lives the NumberFormatException error.
How do to solve it?
The function that we will work on is the one that you pass from file to an array in
private static int[][] getArray(String filename) throws FileNotFoundException{
The of the function is after we read the file.
As you said, you are leading with a 2d array so to insert all the numbers we need to have loops for each dimension on the array.
So we will start from there.
I will use a while beacause we are dealing with a string and it's easier to verify the text that its left on the line. Will add a new int variable that starts in 0 to pass in every column of a line to use with the while loop. And with this we got this:
for (int i = 0; i < lines.length; i++) {
while(!"".equals(line)){
whileIterator++;
}
whileIterator = 0;
}
Next setep, we will divide in 2 behaviors because we will substring the String that has in the line, and will work differently when it's the last number that we are verifying:
for (int i = 0; i < lines.length; i++) {
while(!"".equals(line)){
if(whileIterator + 1 == size){//If its the last iteration that we need in a line
}else{//All other iterations
whileIterator++;
}
whileIterator = 0;}
To finalize let's add the new logic to insert in nos array. So lets pick all line for example 2 7 6 and we want to add the number 2, so lets do that. You just need to substring(int startIndex, int finalIndex) the line and add to the nos array. After that let remove the number and the space ("2 ") from the line that we are veryfying.
for (int i = 0; i < lines.length; i++) {
while(!"".equals(line)){
if(whileIterator + 1 == size){//If its the last iteration that we need
nos[rows][whileIterator] = Integer.parseInt(line.substring(0));//Add to array
line = "";//To not pass the while verification
}else{//All other iterations
nos[rows][whileIterator] = Integer.parseInt(line.substring(0, line.indexOf(" ")));//Add to array
line = line.substring(line.indexOf(" ") + 1);//remove the number we added behind
}
whileIterator++;
}
whileIterator = 0;}
And here you go, that how you add the numbers to an array and don't get the error.
If you need some further explanation just ask. Hope it helps :)

Separate text in k-shingles without Scanner.class in Java

I am trying to separate a text in k-shingles, sadly I cannot use scanner. If the last shingle is too short, I want to fill up with "_". I came this far:
public class Projektarbeit {
public static void main(String[] args) {
testKShingling(7, "ddssggeezzfff");
}
public static void testKShingling(int k, String source) {
//first eliminate whitespace and then fill up with withespaces to match target.length%shingle.length() == 0
String txt = source.replaceAll("\\s", "");
//get shingles
ArrayList<String> shingles = new ArrayList<String>();
int i;
int l = txt.length();
String shingle = "";
if (k == 1) {
for(i = 0; i < l; i++){
shingle = txt.substring(i, i + k);
shingles.add(shingle);
};
}
else {
for(i = 0; i < l; i += k - 1){
try {
shingle = txt.substring(i, i + k);
shingles.add(shingle);
}
catch(Exception e) {
txt = txt.concat("_");
i -= k - 1;
};
};
}
System.out.println(shingles);
}
}
Output: [ddssgge, eezzfff, f______]
It works almost, but in the with the given parameters in the example the last shingle is not necessary (it should be [ddssgge, eezzfff]
Any idea how to do this more beautiful?
To make the code posted work you only need to add break and the end of the catch block:
catch(Exception e) {
txt = txt.concat("_");
i -= k - 1;
break;
};
Having said that I wouldn't use an Exception to control the program. Exception are just that: should be used for run time errors.
Avoid StringIndexOutOfBoundsException by controlling the loop parameters:
public static void main(String[] args) {
testKShingling(3, "ddssggeezzfff");
}
public static void testKShingling(int substringLength, String source) {
//todo validate input
String txt = source.replaceAll("\\s", "");
//get shingles
ArrayList<String> shingles = new ArrayList<>();
int stringLength = txt.length();
if (substringLength == 1) {
for(int index = 0; index < stringLength; index++){
String shingle = txt.substring(index, index + substringLength);
shingles.add(shingle);
};
}
else {
for(int index = 0; index < stringLength -1 ; index += substringLength - 1){
int endIndex = Math.min(index + substringLength, stringLength);
String shingle = txt.substring(index, endIndex);
if(shingle.length() < substringLength){
shingle = extend(shingle, substringLength);
}
shingles.add(shingle);
};
}
System.out.println(shingles);
}
private static String extend(String shingle, int toLength) {
String s = shingle;
for(int index = 0; index < toLength - shingle.length(); index ++){
s = s.concat("_");
}
return s;
}
An alternative implementation of testKShingling:
public static void testKShingling(int substringLength, String source) {
//todo validate input
String txt = source.replaceAll("\\s", "");
ArrayList<String> shingles = new ArrayList<>();
if (substringLength == 1) {
for(char c : txt.toCharArray()){
shingles.add(Character.toString(c));
};
}
else {
while(txt.length() > substringLength) {
String shingle = txt.substring(0, substringLength);
shingles.add(shingle);
txt = txt.substring(substringLength - 1); //remove first substringLength - 1 chars
}
if(txt.length() < substringLength){ //check the length of what's left
txt = extend(txt, substringLength);
}
shingles.add(txt); //add what's left
}
System.out.println(shingles);
}

How to copy a table to another table greater by 1

I cant use Lists, it must be in tables. How to copy a table to another table greater by 1? Im adding some elements to my table and if there is not enough space i want create new/copy table greater by 1.
Code:
Scanner sc = new Scanner(System.in);
String addNew;
String[] newTab = new String[1];
addNew = sc.next();
for(int i = 0; i<newTab.length; i++) {
if (newTab[i] == null) {
newTab[i] = addNew;
}
else {
//here i want to create new table greater than first one
}
}
Trying with Array.CopyOf but still got error java.lang.ArrayIndexOutOfBoundsException: 1
Code:
int defTab = 1;
for(int i = 0; i<newTab.length; i++) {
if (newTab[i] == null) {
newTab[i] = addNew;
//f
for(int j=0; j<newTab.length; j++) {
System.out.println("array content "+newTab[j]);
}
}
else {
String[] newTab2 = Arrays.copyOf(newTab, defTab+1);
for(int j = 0; j<newTab2.length; j++) {
if (newTab2[j] == null) {
newTab2[j] = addNew;
//f
for(int k=0; k<newTab2.length; k++) {
System.out.println("array content "+newTab[k]);
}
}
}
}
}

Java Read Each Line Into Separate Array

I have 1,000 lines of data in a text file and I would like each line to be its own float [].
1,1,1,1,1,1
2,2,2,2,2,2
3,3,3,3,3,3
Would result in:
float[0] = {1,1,1,1,1,1}
float[1] = {2,2,2,2,2,2}
float[2] = {3,3,3,3,3,3}
Is this possible? I could only find examples of loading an entire file into an array. I tried hardcoding all the arrays, but exceeded the byte character limit of ~65,000
Try the following:
// this list will store all the created arrays
List<float[]> arrays = new ArrayList<float[]>();
// use a BufferedReader to get the handy readLine() function
BufferedReader reader = new BufferedReader(new FileReader("myfile.txt"));
// this reads in all the lines. If you only want the first thousand, just
// replace these loop conditions with a regular counter variable
for (String line = reader.readLine(); line != null; line = reader.readLine()) {
String[] floatStrings = line.split(",");
float[] floats = new float[floatStrings.length];
for (int i = 0; i < floats.length; ++i) {
floats[i] = Float.parseFloat(floatStrings[i]);
}
arrays.add(floats);
}
Note that I haven't added any exception handling (readLine(), for example, throws IOException).
use a LineIterator to read each line without loading the whole file
for each line, use a regular expression to extract figures like (\d\.)+ and iterator over the matches found with methods like find() and group()
<body>
<pre>
import java.io.FileReader;
public class Check {
public static void main(String[] args) {
readingfile();
}
public static void readingfile() {
try {
FileReader read = new FileReader("D:\\JavaWkspace\\numbers.txt");
int index;
String nums1 = "";
while ((index = read.read()) != -1) {
if (((char) index) != '\n') {
nums1 += String.valueOf((char) index);
}
}
System.out.println("Problem statement: Print out the greatest number on each line:\n" + nums1);
String f = nums1.substring(0, 14);
String s = nums1.substring(15, 29);
String t = nums1.substring(30);
String[] fs = f.split(",");
int size = fs.length;
int[] arr = new int[size];
for (int i = 0; i < size; i++) {
arr[i] = Integer.parseInt(fs[i]);
}
int max = arr[0];
for (int i = 0; i < arr.length; i++) {
if (max < arr[i]) {
max = arr[i];
}
}
System.out.println("\nGreatest number in the first line is:" + (max));
String[] sstr = s.split(",");
int size2 = sstr.length;
int[] arr2 = new int[size2];
for (int i = 0; i < size2; i++) {
arr2[i] = Integer.parseInt(sstr[i]);
}
int max2 = arr2[0];
for (int i = 0; i < arr2.length; i++) {
if (max2 < arr2[i]) {
max2 = arr2[i];
}
}
System.out.println("\nGreatest number in the second line is:" + (max2));
String[] str3 = t.split(",");
int size3 = str3.length;
int[] arr3 = new int[size3];
for (int i = 0; i < size3; i++) {
arr3[i] = Integer.parseInt(str3[i]);
}
int max3 = arr3[0];
for (int i = 0; i < arr3.length; i++) {
if (max3 < arr3[i]) {
max3 = arr3[i];
}
}
System.out.println("\nGreatest number in the third line is:" + (max3));
read.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
</pre>
</body>
Loop over the line-delimited contents of the file with .split("\n") and then cast each result as float array. Here's how to convert the string into a float for you => http://www.devdaily.com/java/edu/qanda/pjqa00013.shtml

Sorting Java Multidimensional Array

I'm trying to sort the contents of an array and while it seems to be working (no runtime errors; is performing sort tasks), the first 10 rows, while sorted, are not in order with the rest of the rows.
class coordSort.java
import java.io.*;
import java.util.Arrays;
import java.util.Scanner;
public class coordSort {
#SuppressWarnings({ "unchecked", "unused" })
public static void main (String args[]) throws IOException {
String xCoord, yCoord;
int coordSum;
Scanner input = new Scanner(System.in);
//Get x coordinate from user
System.out.print("Enter x coordinate: ");
xCoord = input.next();
//Get x coordinate from user
System.out.print("Enter y coordinate: ");
yCoord = input.next();
boolean sort = false;
char[] a = xCoord.toCharArray();
char[] b = yCoord.toCharArray();
//validate user input is a digit
if ( (Character.isDigit(a[0])) ) {
if(Character.isDigit(b[0]) ){
//digits entered - begin processing all coordinate values
sort = true;
}
}
//If validation failed, inform user
if(!sort){
System.out.println("Please enter a positive numeric value.");
}
if(sort){
//determine SUM of user entered coordinates
coordSum = Integer.parseInt(xCoord) + Integer.parseInt(yCoord);
//define coordinate array
String[][] coordUnsortedArray = new String[26][3];
int counter;
int commaCount;
String xCoordIn, yCoordIn;
int intXCoordIn, intYCoordIn, sumCoordIn, coordDiff;
//define input file
FileInputStream fileIn = new FileInputStream("coords.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(fileIn));
for (int j = 0; j < coordUnsortedArray.length; j++){
counter = 0;
commaCount = 0;
//line from file to variable
String coordSet = reader.readLine();
//look for the second "," to determine end of x coordinate
for(int k = 0; k < coordSet.length(); k++){
if (coordSet.charAt(k) == ',') {
commaCount++;
counter++;
if (commaCount == 2){
break;
}
}else{
counter++;
}
}
//define x coordinate
xCoordIn = (coordSet.substring(2,(counter - 1)));
intXCoordIn = Integer.parseInt(xCoordIn);
//define y coordinate
yCoordIn = (coordSet.substring((counter),coordSet.length()));
intYCoordIn = Integer.parseInt(yCoordIn);
//coordinate calculations
sumCoordIn = Integer.parseInt(xCoordIn) + Integer.parseInt(yCoordIn);
coordDiff = sumCoordIn - coordSum;
//load results to array
coordUnsortedArray[j][0] = xCoordIn;
coordUnsortedArray[j][1] = yCoordIn;
coordUnsortedArray[j][2] = Integer.toString(coordDiff);
//Output Array (BEFORE SORTING)
//System.out.println((j + 1) + ") " + coordUnsortedArray[j][0] + " : " + coordUnsortedArray[j][1] + " : " + coordUnsortedArray[j][2]);
}
System.out.println("\n");
fileIn.close();
String[][] coordsSorted = new String[26][3];
//Sort array coordDiff, column 3
Arrays.sort(coordUnsortedArray, new ColumnComparator(2));
//Print the sorted array
for(int i = 0; i < coordUnsortedArray.length; i++){
String[] row = coordUnsortedArray[i];
System.out.print((i + 1) + ") ");
for(int j = 0; j < row.length; j++) {
//System.out.print(row[j] + " | ");
coordsSorted[i][j] = row[j];
System.out.print(coordsSorted[i][j] + " : ");
}
System.out.print("\n");
}
}
}
}
class sortCoords.java --
import java.util.Comparator;
#SuppressWarnings("rawtypes")
class ColumnComparator implements Comparator {
int columnToSort;
ColumnComparator(int columnToSort) {
this.columnToSort = columnToSort;
}
//overriding compare method
public int compare(Object o1, Object o2) {
String[] row1 = (String[]) o1;
String[] row2 = (String[]) o2;
//compare the columns to sort
return row1[columnToSort].compareTo(row2[columnToSort]);
}
//overriding compare method
public int compare1(Object o1, Object o2) {
String[] row1 = (String[]) o1;
String[] row2 = (String[]) o2;
//compare the columns to sort
return row1[columnToSort].compareTo(row2[columnToSort]);
}
}
I am trying to sort the array in numerical order by the 3rd column. The unsorted array is populated by a text file containing something like:
a,44,67
b,31,49
c,93,6
I am performing calculations on the array compared to user input and populating the array as follows:
44,67,101
31,49,70
93,6,89
I would like the sortedArray to output the following:
31,49,70
93,6,89
44,67,101
One possible confusion here:
return row1[columnToSort].compareTo(row2[columnToSort])
This is a string comparison, not a numerical one. If you sort based on strings, you will get different results than if you do by numbers - ie "1","10","100","9" vs 1,9,10,100
Check out Integer.parseInt and if you can't figure out the rest, feel free to ask more questions.
As spinning_plate stated. You need to compare their int values i.e. you need a cast there
int num1 = Integer.parseInt(row1[columnToSort]);
int num2 = Integer.parseInt(row2[columnToSort]);
if(num1 > num2)
return 1;
else
return 0;
Place this code in the compareTo method and check. Swap the return statements to sort in reverse order.
Also, adding some error checking in the compareTo method will make the code more efficient.
Ok, so after the assistance provided here, below is the solution that we found. Thanks again for the help everyone! Hopefully the code below helps someone else out.
Code for class1 --
import java.io.*;
import java.util.Arrays;
import java.util.Scanner;
public class coordSort {
#SuppressWarnings({ "unchecked" })
public static void main (String args[]) throws IOException {
String xCoordChar, yCoordChar;
int xCoord, yCoord, coordSum;
Scanner input = new Scanner(System.in);
//Get x coordinate from user
System.out.print("Enter x coordinate: ");
xCoordChar = input.next();
//Get x coordinate from user
System.out.print("Enter y coordinate: ");
yCoordChar = input.next();
boolean sort = false;
char[] a = xCoordChar.toCharArray();
char[] b = yCoordChar.toCharArray();
//validate user input is a digit
if ( (Character.isDigit(a[0])) ) {
if(Character.isDigit(b[0]) ){
//digits entered - begin processing all coordinate values
sort = true;
}
}
//If validation failed, inform user
if(!sort){
System.out.println("Please enter a positive numeric value.");
}
if(sort){
//Parse user input characters to Integers
xCoord = Integer.parseInt(xCoordChar);
yCoord = Integer.parseInt(yCoordChar);
//determine SUM of user entered coordinates
coordSum = xCoord + yCoord;
//define coordinate array
int[][] coordUnsortedArray = new int[26][3];
int counter;
int commaCount;
String xCoordIn, yCoordIn;
int intXCoordIn, intYCoordIn, sumCoordIn, coordDiff;
//define input file
FileInputStream fileIn = new FileInputStream("coords.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader (fileIn));
for (int j = 0; j < coordUnsortedArray.length; j++){
counter = 0;
commaCount = 0;
//line from file to variable
String coordSet = reader.readLine();
//look for the second "," to determine end of x coordinate
for(int k = 0; k < coordSet.length(); k++){
if (coordSet.charAt(k) == ',') {
commaCount++;
counter++;
if (commaCount == 2){
break;
}
}else{
counter++;
}
}
//define x coordinate
xCoordIn = (coordSet.substring(2,(counter - 1)));
intXCoordIn = Integer.parseInt(xCoordIn);
//define y coordinate
yCoordIn = (coordSet.substring((counter),coordSet.length()));
intYCoordIn = Integer.parseInt(yCoordIn);
//coordinate calculations
sumCoordIn = Integer.parseInt(xCoordIn) + Integer.parseInt (yCoordIn);
coordDiff = sumCoordIn - coordSum;
if (coordDiff < 0){
coordDiff = coordDiff * (-1);
}
//load results to array
coordUnsortedArray[j][0] = intXCoordIn;
coordUnsortedArray[j][1] = intYCoordIn;
coordUnsortedArray[j][2] = coordDiff;
}
fileIn.close();
System.out.print("\n");
System.out.println("Array Before Sorting:");
System.out.println("=====================");
//Array Before Sorting
for(int i = 0; i < coordUnsortedArray.length; i++){
int[] row = coordUnsortedArray[i];
System.out.print((i + 1) + ") ");
for(int j = 0; j < (row.length - 1); j++) {
coordUnsortedArray[i][j] = row[j];
if(j < 1){
System.out.print(coordUnsortedArray [i] [j] + ",");
}else{
System.out.println(coordUnsortedArray [i] [j]);
}
}
}
System.out.print("\n");
System.out.print("\n");
//Sort array coordDiff, column 3
Arrays.sort(coordUnsortedArray, new ColumnComparator(2));
System.out.println("Array After Sorting:");
System.out.println("====================");
//Original Array After Sorting
for(int i = 0; i < coordUnsortedArray.length; i++){
int[] row = coordUnsortedArray[i];
System.out.print((i + 1) + ") ");
for(int j = 0; j < (row.length - 1); j++) {
coordUnsortedArray[i][j] = row[j];
if(j < 1){
System.out.print(coordUnsortedArray[i][j] + ",");
}else{
System.out.println(coordUnsortedArray [i] [j]);
}
}
}
}
}
}
Code for class2 --
import java.util.Comparator;
#SuppressWarnings("rawtypes")
class ColumnComparator implements Comparator {
int columnToSort;
ColumnComparator(int columnToSort) {
this.columnToSort = columnToSort;
}
//Compare method
public int compare(Object o1, Object o2) {
int[] row1 = (int[]) o1;
int[] row2 = (int[]) o2;
int intRow1 = (row1[columnToSort]);
int intRow2 = (row2[columnToSort]);
return new Integer(intRow1).compareTo(new Integer(intRow2));
}
}

Categories

Resources