【问题标题】:Sorting Java Multidimensional Array对 Java 多维数组进行排序
【发布时间】:2012-04-22 01:10:16
【问题描述】:

我正在尝试对数组的内容进行排序,虽然它似乎正在工作(没有运行时错误;正在执行排序任务),但前 10 行在排序时与其余行不按顺序排列.

类 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]);
    }
} 

我正在尝试按第 3 列的数字顺序对数组进行排序。未排序的数组由包含以下内容的文本文件填充:

a,44,67

b,31,49

c,93,6

与用户输入相比,我正在对数组执行计算并按如下方式填充数组:

44,67,101

31,49,70

93,6,89

我希望 sortedArray 输出以下内容:

31,49,70

93,6,89

44,67,101

【问题讨论】:

  • 欢迎 - 如果您能阐明您希望它们如何排序,也许是现在的输出以及正确输出的示例,这将有所帮助。
  • 您好,感谢您的快速响应。我正在尝试按第三列按数字顺序对数组进行排序。未排序的数组由包含以下内容的文本文件填充:a,44,67 b,31,49 c,93,6 与用户输入相比,我正在对数组执行计算并按如下方式填充数组:44,67,101 31 ,49,70 93,6,89 我希望 sortedArray 输出以下内容: 31,49,70 93,6,89 44,67,101

标签: java sorting multidimensional-array comparator


【解决方案1】:

这里有一个可能的混淆:

 return row1[columnToSort].compareTo(row2[columnToSort])

这是一个字符串比较,而不是数字比较。如果您根据字符串排序,您将得到与按数字排序不同的结果 - 即 "1","10","100","9" vs 1,9,10,100

查看Integer.parseInt,如果您不知道其余的,请随时提出更多问题。

【讨论】:

  • 请看我上面的回复。
  • 我认为你写的和我的回答是一致的,看我的编辑
  • 我想知道您是否可以在下面查看我的错误?我似乎无法让它工作......任何想法,建议或例子都会很有帮助。再次感谢到目前为止所做的一切!
【解决方案2】:

正如 spin_plate 所说。您需要比较它们的 int 值,即您需要在那里进行演员表

    int num1 = Integer.parseInt(row1[columnToSort]);
    int num2 = Integer.parseInt(row2[columnToSort]);
    if(num1 > num2)
            return 1;
    else 
            return 0;

将此代码放在 compareTo 方法中并检查。交换返回语句以倒序排序。

此外,在compareTo 方法中添加一些错误检查将使代码更高效。

【讨论】:

  • 再次感谢您的回复。输入时:return Integer.parseInt(row1[columnToSort]).Integer.parseInt(compareTo(row2[columnToSort]));我在第二个 Integer 和 compareTo 下有错误我很抱歉,但我是 Java 新手...
  • 我的错误。括号和 parseInt 在错误的位置。修复。请尝试让我知道任何错误。
  • 现在整行都出错了。错误说,“不能在原始类型 int 上调用 compareTo(int)”。
  • 所以我尝试了几种不同的方法来消除错误,但似乎无法正确...我发现如果我更改 "String[] row1 = (String[] ) o1;"到“int[] row1 = (int[]) o1;”,只有 parseInt 显示错误,但我确定这是因为变量类型已更改。如果我删除解析,那么整行会再次出现“无法在原始类型 int 上调用 compareTo(int)”的错误。我很茫然。任何进一步的提示和建议都非常感谢。再次感谢您的回复!
  • 您好,感谢您的更新。鳕鱼正在运行,只是现在输出根本没有排序。我想我理解这个想法是什么 - 转换为 int 变量类型以进行正确排序,然后,如果 num1
【解决方案3】:

好的,在此处提供帮助之后,以下是我们找到的解决方案。再次感谢大家的帮助!希望下面的代码可以帮助其他人。

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]);
                    }
                }
            }
            }
        }
}

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));
}
}    

【讨论】:

  • 没有。该代码无法按您预期的方式工作。它不会排序,也不会正确显示值。
猜你喜欢
  • 2010-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-23
  • 2014-02-25
相关资源
最近更新 更多