0
 import java.util.*;;

    public class selection {
    Scanner in=new Scanner(System.in);
    private int size;
    private int[] num=new int[size];

    selection(int size){
      this.size=size;
             }
    void enternum(){
        System.out.print("enter number"+size);
        for (int i=0;i<5;i++)
            num[i]=in.nextInt();

    }

    void sort(){
        for (int i=0;i<num.length;i++){
        int min=i;

        for(int j=i+1;j<num.length;j++){

                if(less(num[i],num[j]))
                    excg(i,j);
        }
    }

     display();

    }

    boolean less(int x,int y){
        if(x>y)
            return true;
        else
            return false;

    }

    void excg(int i,int j){

        num[i]=num[j];
        num[j]=num[i];
    }


    void display(){
        for(int i=0;i<num.length;i++)
            StdOut.println(num[i]);
    }

 public static void main (String[] arg){
        Scanner in=new Scanner(System.in);
       System.out.print("enter total num of the array");
        int size=in.nextInt();

        selection obj=new selection(size);
        obj.enternum();
        obj.sort();
    }
 }

when we enter the direct value of the size i.e size=5 then it is working but whenwe enter throughkey board then it is giving error aaray out of box .i am taking input through scanner class using nextInt() method

2 Answers 2

1

That's because you allocate the array to be size 0. If you allocate it after you read in the size, instead of before, then it'll work.

Sign up to request clarification or add additional context in comments.

Comments

1

Initilize the array at the constructor. By deafult int class member(size) initialized with 0.

private int[] num;

selection(int size){
    //this.size=size;  //not required. 
    num=new int[size];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.