Home > other >  How to sort a array with a function and using a code like this in java
How to sort a array with a function and using a code like this in java

Time:05-14

Hello i have a java Code where i the Programm should sort the variable num but it only gives out some weird strings. I would like if you could help my with some tipps. The code needs to give out 1,4,6,9 i hope everyone understands what's about.

public class A3 {

public static void meinefunktion(int[] num, int temp, int i, int j) {

    if (num[j] < num[i]) {
        temp = num[i];
        num[i] = num[j];
        num[j] = temp;
    }
}

public static void main(String[] args) {

    int[] num = { 4, 9, 6, 1 };
    int temp;
    temp = 0;
    int i = 0;
    while (i < num.length) {
        int j = i   1;
        while (j < num.length) {
            meinefunktion(num, temp, i, j);
            j  = 1;
        }
        i  = 1;
    }
    System.out.println(num);

  }
}

CodePudding user response:

You can do it in the main function as bellow :

public static void main(String[] args) {

    int[] num = { 4, 9, 6, 1 };
    Arrays.sort(num);

   for (int j : num){
       System.out.println(j);
   }

}

CodePudding user response:

You are printing the array directly which, in Java, doesn't print the single elements, but a generated reference string. Generally, you can convert arrays into a List object which overrides its toString method, properly. Depending on your version of Java there are the following options:

java.util.Arrays.toList(...)

or:

java.util.List.of(...)

Unfortunately, this doesn't work for primitive array component types (such as int). You need to use the boxed type Integer:

package com.yaypay;

import java.util.Arrays;

public class AaaTest {
    public static void meinefunktion(Integer[] num,  int i, int j) {

        if (num[j] < num[i]) {
            int temp = num[i];
            num[i] = num[j];
            num[j] = temp;
        }
    }

    public static void main(String[] args) {

        Integer[] num = { 4, 9, 6, 1 };
        int i = 0;
        while (i < num.length) {
            int j = i   1;
            while (j < num.length) {
                meinefunktion(num, i, j);
                j  = 1;
            }
            i  = 1;
        }
        System.out.println(Arrays.asList(num));

    }
}

CodePudding user response:

Yes, your code does exactly what you need! The only minor missing point is the printing statement - System.out.println(num). Instead of it, you may please loop over the array to print the results as shown below. This sample code uses while loop since you already know it.

int index = 0;
while (index < num.length) {
    System.out.println(num[index]);
    index  ;
}
  • Related