Red Velasco
Red Velasco

Reputation: 103

Printing whats inside the array

            if (val1.charAt(0) == 'A' || val1.charAt(0) == 'a')
            {
                System.out.println("Numbers in Ascending Order:");
                    for (int asc : numx) 
                    {   
                        System.out.print (asc + " ");
                    }

            }
            if (val1.charAt(0) == 'D' || val1.charAt(0) == 'd')
            {
                System.out.println("Numbers in Descending Order:");
                    for (int desc : numx) 
                        {   
                            System.out.print (desc + " ");
                        }
            }

        }   
    }
}

Hello im almost finish with this code..

I would like to know how do you sort numbers in Ascending and Descending .. the one in asc/desc?

Upvotes: 0

Views: 60

Answers (4)

Bhoot
Bhoot

Reputation: 2633

You can sort the numbers using the following:

Arrays.sort(numx);

Then based on whether you have to print the array in ascending or descending order, print the array in forward or reverse order.

You may use the following method:

String asc = "";
String dsc = "";
for(int num: numx) {
    asc += num + "\n";
    dsc = num + "\n" + dsc;
}
val1.charAt(0) == 'A' || val1.charAt(0) == 'a' ?  System.out.println(asc)
: System.out.println(dsc);

Upvotes: 1

Md. Miraz Kabir
Md. Miraz Kabir

Reputation: 1

//Use this to sort in ascending order

int max = 0; int temp = 0; int count = 0;

for(int c=0;c<numx.length-1;++c){
    max = numx[c];
    count = c;
    for(int v=c+1;v<numx.length;++v){
        if(numx[v]>max){
            max = numx[v];
            count = c;
        }
    }
    temp = numx[c];
    numx[c] = max;
    numx[count] = temp;
}

//The same goes for descending order but the logic would be (numx[v] < max)

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201439

If I understand you, could might use Arrays.toString(int[]) like

System.out.println("Accepted numbers are:" + Arrays.toString(numx));

Upvotes: 1

Sam Estep
Sam Estep

Reputation: 13304

If you mean to print all values in numx, I suppose the simplest way would be this:

for (int number : numx) {
  System.out.print(number + " ");
}

That's assuming that you want to use the format you specified in your question (just one space between each item, no other decoration).

Upvotes: 2

Related Questions