I am creating a program which will make the user input integer (one after another), stored in array and display the integers in descending order. The program also ask to the user to input a string convert it to char using string.toCharArray()
. I've correctly done displaying the integer into descending order. The problem is I don't know how to display the char descendingly.
This is the code for the integer:
for(i=0;i<nums.length;i++){
System.out.print("Enter value for index["+i+"] here --> ");
nums[i]=Integer.parseInt(br.readLine());}
while(pass<nums.length){
for(i=0;i<(nums.length-pass);i++){
if(nums[i]<nums[i+1]){
temp=nums[i];
nums[i]=nums[i+1];
nums[i+1]=temp;
}
}
pass++;
}
System.out.println("\n\nThe numbers when sorted descendingly are :\n");
for(i=0;i<nums.length;i++){
System.out.println(nums[i]);
This is the code for the string to array. This is where i'm having problems. I don't have errors in running the program just it's just I don't how to do it correctly.
System.out.print("Input a string");
String strValue= br.readLine();
char[] chrValues;
chrValues=strValue.toCharArray( );
while(flag<chrValues.length){
for (c=0; c< (chrValues.length- flag); c++){
if(chrValues[c]<chrValues[i+1]){
tempo=chrValues[c];
chrValues[c]=chrValues[c+1];
chrValues[c+1]= tempo;}
}
}
flag++;
System.out.println("\n\nThe String when converted in character and sorted descendingly are :\n");
for(c=0;i<chrValues.length;c++){
System.out.println(chrValues[c]);}
By the way, I used flag as a temporary array storage.
Best Answer
You already have built-in method for that: -
For descending order, you can define a
Comparator
and pass that toArrays.sort()
method..You can use Arrays#sort and ArrayUtils#toObject for sorting in
Descending order
..Here's how it works: -