Home > Mobile >  Running class inside function
Running class inside function

Time:12-03

I am a new learner to Java; I want to run a class method inside a function thats not within the class scope inside VSC. However, my compiler tells me I have to remove the last curly braces from the class and require to instantiate the function as a method inside the class.

How do I use these in a dependent way?

For example:

import java.lang.Integer;

public class sortArray{

    public static void reorder(int[] T, int pos, int min){
        int i = 1;
        //int[] temp = new int[T.length];
        for( i = 1; i < T.length; i  ){
            pos = i;
            min = T[i];
            for(int j = i 1; j < T.length; i  ){
                if(Integer.compare(T[j], min) < 0){
                    pos=j;
                    min=T[j];
                    T[pos] = T[i];
                    T[i] = min; } }}}}


public static void read(){
    // run the class inside here
}

I come from a python background so best I explain from that background and correct me on the difference.

For example:

class sortArray:
    ....

def read():
    array = sortArray()
    reorder = array.reorder([1, 2, 3], 1, 1)
    return reorder

CodePudding user response:

From your python snippet, the equivalent java might look like this.

class Sorter{
    int[] reorder(int[] a, int pos, int min){
        return a;
    }

    public static void main(String[] args){
      Sorter s = new Sorter();
      int[] reorder = s.reorder( new int[]{1, 2, 3}, 1, 1 );
    }
}

CodePudding user response:

public class SortArray{ //mind the class naming convention
    public static void main(String[] args) {
        AnotherClass.read(); //test purposes
    }
    public static void reorder(int[] T){
        for(int i = 0; i < T.length; i  ){ //can declare inside loop
            int min = T[i];
            for(int j = i 1; j < T.length; j  ){ //prob typo here, you increment i instead of j
                if(T[j] < min){ // no need for Integer.compare here
                    min =T[j];
                    T[j] = T[i];
                    T[i] = min;
                }
            }
        }
    }
}

class AnotherClass {
    public static void read(){
        int[] T = {4,3,3,5,9,7};
        // your call to the class aka static method, 
        // mind that the caller method also needs to be static
        SortArray.reorder(T); 
        System.out.println(Arrays.toString(T));
    }
}

Output is [3, 3, 4, 5, 7, 9]

  •  Tags:  
  • java
  • Related