1

so I NEED to sort this array by column and populate it bu user input. so this is my code and if you can help me it would be great..

public class JavaApplication45 {
    
    public static void main(String[] args) throws IOException {
           
    String[][] AN = new String[8][5];

    AN[0][0] = "Curepipe";
    AN[0][1] = "-20.3162";
    AN[0][2] = "57.5166";
    AN[0][3] = "Plaine Wilhems";

    AN[1][0] = "Ebene";
    AN[1][1] = "-20.2456";
    AN[1][2] = ``"57.4842 ";
    AN[1][3] = "Plaine Wilhems ";

    AN[2][0] = "Rose Hill";
    AN[2][1] = "-20.2456";
    AN[2][2] = "57.4719";
    AN[2][3] = "Plaine Wilhems";

    AN[3][0] = "Beau Bassin";
    AN[3][1] = "-20.2276";
    AN[3][2] = "57.4681";
    AN[3][3] = "Plaine Wilhems";

    AN[4][0] = "Quatre Bornes";
    AN[4][1] = "-20.2654";
    AN[4][2] = "57.4778 ";
    AN[4][3] = "Plaine Wilhems";

    AN[5][0] = "Vacoas";
    AN[5][1] = "-20.2981";
    AN[5][2] = "57.4783";
    AN[5][3] = "Plaine Wilhems";

    AN[6][0] = "Mahebourg";
    AN[6][1] = "20.4081";
    AN[6][2] = "57.7000 ";
    AN[6][3] = "Grand Port    ";

    AN[7][0] = "Goodlands";
    AN[7][1] = "-20.0350";
    AN[7][2] = "57.6431";
    AN[7][3] = "Rivere du Rempart";


 int rows = 8;
    int columns = 4;
    int a, b;
    for (a = 0; a < rows; a++) {
        for (b = 0; b < columns; b++) {
            System.out.print(AN[a][b] + " \t");

        }
        System.out.println(" ");

    }

so I NEED to sort this array by column and populate it bu user input. so this is my code and if you can help me it would be great..

  • Possibly related: [java Arrays.sort 2d array](https://stackoverflow.com/q/15452429), [trying to fill a 2D array by user-input how to do it?](https://stackoverflow.com/q/27654491) – Pshemo Jul 16 '21 at 18:23

3 Answers3

1

To sort by an arbitrary column, you can use Comparator.comparing.

int columnIndex = 0;
Arrays.sort(AN, Comparator.comparing(x -> x[columnIndex]));

To allow the user to enter the values for the array, you can use a Scanner to read input.

try(Scanner sc = new Scanner(System.in)){
    for(int i = 0; i < AN.length; i++){
        for(int j = 0; j < AN[i].length; j++){
            System.out.print("Enter value: ");
            AN[i][j] = sc.nextLine();
        }
    }
}
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
  • @Leo Happy to help. – Unmitigated Jul 16 '21 at 19:51
  • Very good use of `Comparator`! The only concern I see with your answer is the use of `Scanner` with try-with-resources. The `Scanner` for `System.in` should not be closed; otherwise, `System.in` will also be closed and there is no way to reopen it without restarting the JVM. This will cause an exception if any other part of the application is using `System.in`. The `Scanner` for file is a good candidate to be used with try-with-resources. – Arvind Kumar Avinash Jul 17 '21 at 08:39
0

As per your code i understand that you want print 5 column which is Postcode i implemented this column dynamically as per your 2nd 2D array values, check out my code and it's output and confirm me is this answer useful to you or not

import java.util.*;

    public class JavaApplication45 {
    
    public static void main(String[] args) throws IOException {
           
    String[][] AN = new String[8][5];

    AN[0][0] = "Curepipe";
    AN[0][1] = "-20.3162";
    AN[0][2] = "57.5166";
    AN[0][3] = "Plaine Wilhems";

    AN[1][0] = "Ebene";
    AN[1][1] = "-20.2456";
    AN[1][2] = "57.4842 ";
    AN[1][3] = "Plaine Wilhems ";

    AN[2][0] = "Rose Hill";
    AN[2][1] = "-20.2456";
    AN[2][2] = "57.4719";
    AN[2][3] = "Plaine Wilhems";

    AN[3][0] = "Beau Bassin";
    AN[3][1] = "-20.2276";
    AN[3][2] = "57.4681";
    AN[3][3] = "Plaine Wilhems";

    AN[4][0] = "Quatre Bornes";
    AN[4][1] = "-20.2654";
    AN[4][2] = "57.4778 ";
    AN[4][3] = "Plaine Wilhems";

    AN[5][0] = "Vacoas";
    AN[5][1] = "-20.2981";
    AN[5][2] = "57.4783";
    AN[5][3] = "Plaine Wilhems";

    AN[6][0] = "Mahebourg";
    AN[6][1] = "20.4081";
    AN[6][2] = "57.7000 ";
    AN[6][3] = "Grand Port    ";

    AN[7][0] = "Goodlands";
    AN[7][1] = "-20.0350";
    AN[7][2] = "57.6431";
    AN[7][3] = "Rivere du Rempart";
    
    //zip table
    String[][] str1 = new String[8][2];

    str1[0][0] = "Curepipe";
    str1[0][1] = "74415";

    str1[1][0] = "Goodlands";
    str1[1][1] = "30401";

    str1[2][0] = "Rose Hill";
    str1[2][1] = "71360";

    str1[3][0] = "Beau Bassin";
    str1[3][1] = "71401";

    str1[4][0] = "Vacoas";
    str1[4][1] = "73304";

    str1[5][0] = "Mahebourg";
    str1[5][1] = "50810";

    str1[6][0] = "Quatre Bornes";
    str1[6][1] = "72249";

    str1[7][0] = "Ebene";
    str1[7][1] = "72201";


    System.out.println("City     \tLat      \tlong      \tDistrict \t\tPostcode");
    System.out.println("-----------------------------------------------------------------------------------");
    int rows = 8;
    int columns = 5;
    int a, b, c;
    
    for (a = 0; a < rows; a++) {
        for (b = 0; b < columns; b++) {
            if(b<4){
                //use to formate values
                Formatter formatter = new Formatter();
                formatter.format( "%-7s",AN[a][b]);
                System.out.print(formatter + " \t");
            }else{
                for(c=0;c<rows;c++){
                    if(AN[a][0]==str1[c][0]){
                        if(AN[a][3].length()>14){
                        //use to formate values
                        Formatter formatter = new Formatter();
                        formatter.format("%2s", str1[c][1]);
                        System.out.print(formatter + "  ");
                        }else{
                        //use to formate values
                        Formatter formatter = new Formatter();
                        formatter.format("%13s", str1[c][1]);
                        System.out.print(formatter + "  ");
                        }
                        
                         
                    }
                }
            }
            
        }
      
        System.out.println(" ");
        
    }
  }
     

}

Output : enter image description here

saqib kafeel
  • 296
  • 3
  • 8
  • now check i updated answer as per your formating request , if it is useful to you, you can mark it as answer, thanks – saqib kafeel Jul 16 '21 at 19:42
  • why did you edit and change the question ? kindly mark my answer as answer and generate new question instead of edit the old one – saqib kafeel Jul 16 '21 at 20:02
0

You can use a static field to keep track of the sorted column (sortField). Each time you display the data, grab a the sorting instance with the current field.

import java.util.*;
import java.util.stream.*;

public class JavaApplication45 {
    static String[] fields = { "City", "Lat", "Long", "District", "Postcode" };
    static String[][] data;
    static String[][] zip;
    
    static String sortField;
    static Comparator<String[]> currentComparator;
    
    public static void main(String[] args) {
        display();
        setSortField("City"); // Change the sorting...
        display();
    }
    
    private static void setSortField(String newSortField) {
        if (sortField != newSortField) {
            sortField = newSortField;
            currentComparator = generateComparator();
        }
    }
    
    private static void display() {
        Collection<String[]> lines = getCollection();
        if (currentComparator != null) {
            lines = lines.stream().sorted(currentComparator).collect(Collectors.toList());
        }
        System.out.println(Arrays.stream(fields).collect(Collectors.joining("\t")));
        System.out.println("-".repeat(60));     
        for (String[] line : lines) {
            System.out.println(Stream.of(line).collect(Collectors.joining("\t")));
        }
        System.out.println();
    }
    
    private static Collection<String[]> getCollection() {
        Collection<String[]> lines = new ArrayList<>();
        for (int row = 0; row < data.length; row++) {
            String[] cols = new String[data[row].length + 1];
            for (int col = 0; col < data[row].length; col++) {
                cols[col] = data[row][col];
            }
            cols[data[row].length] = zip[row][1];
            lines.add(cols);
        }
        return lines;
    }
    
    private static Comparator<String[]> generateComparator() {
        int sortIndex = Arrays.asList(fields).indexOf(sortField);
        return new Comparator<String[]>() {
            @Override
            public int compare(String[] left, String[] right) {
                return sortIndex != -1 ? left[sortIndex].compareTo(right[sortIndex]) : 0;
            }
        };
    }

    static {
        data = new String[8][4];
        
        data[0][0] = "Curepipe";
        data[0][1] = "-20.3162";
        data[0][2] = "57.5166";
        data[0][3] = "Plaine Wilhems";

        data[1][0] = "Ebene";
        data[1][1] = "-20.2456";
        data[1][2] = "57.4842";
        data[1][3] = "Plaine Wilhems ";

        data[2][0] = "Rose Hill";
        data[2][1] = "-20.2456";
        data[2][2] = "57.4719";
        data[2][3] = "Plaine Wilhems";

        data[3][0] = "Beau Bassin";
        data[3][1] = "-20.2276";
        data[3][2] = "57.4681";
        data[3][3] = "Plaine Wilhems";

        data[4][0] = "Quatre Bornes";
        data[4][1] = "-20.2654";
        data[4][2] = "57.4778";
        data[4][3] = "Plaine Wilhems";

        data[5][0] = "Vacoas";
        data[5][1] = "-20.2981";
        data[5][2] = "57.4783";
        data[5][3] = "Plaine Wilhems";

        data[6][0] = "Mahebourg";
        data[6][1] = "20.4081";
        data[6][2] = "57.7000";
        data[6][3] = "Grand Port";

        data[7][0] = "Goodlands";
        data[7][1] = "-20.0350";
        data[7][2] = "57.6431";
        data[7][3] = "Rivere du Rempart";

        zip = new String[8][2];

        zip[0][0] = "Curepipe";
        zip[0][1] = "74415";

        zip[1][0] = "Goodlands";
        zip[1][1] = "30401";

        zip[2][0] = "Rose Hill";
        zip[2][1] = "71360";

        zip[3][0] = "Beau Bassin";
        zip[3][1] = "71401";

        zip[4][0] = "Vacoas";
        zip[4][1] = "73304";

        zip[5][0] = "Mahebourg";
        zip[5][1] = "50810";

        zip[6][0] = "Quatre Bornes";
        zip[6][1] = "72249";

        zip[7][0] = "Ebene";
        zip[7][1] = "72201";
    }
}

Output

City    Lat Long    District    Postcode
------------------------------------------------------------
Curepipe    -20.3162    57.5166 Plaine Wilhems  74415
Ebene   -20.2456    57.4842 Plaine Wilhems  30401
Rose Hill   -20.2456    57.4719 Plaine Wilhems  71360
Beau Bassin -20.2276    57.4681 Plaine Wilhems  71401
Quatre Bornes   -20.2654    57.4778 Plaine Wilhems  73304
Vacoas  -20.2981    57.4783 Plaine Wilhems  50810
Mahebourg   20.4081 57.7000 Grand Port  72249
Goodlands   -20.0350    57.6431 Rivere du Rempart   72201

City    Lat Long    District    Postcode
------------------------------------------------------------
Beau Bassin -20.2276    57.4681 Plaine Wilhems  71401
Curepipe    -20.3162    57.5166 Plaine Wilhems  74415
Ebene   -20.2456    57.4842 Plaine Wilhems  30401
Goodlands   -20.0350    57.6431 Rivere du Rempart   72201
Mahebourg   20.4081 57.7000 Grand Port  72249
Quatre Bornes   -20.2654    57.4778 Plaine Wilhems  73304
Rose Hill   -20.2456    57.4719 Plaine Wilhems  71360
Vacoas  -20.2981    57.4783 Plaine Wilhems  50810
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132