Here the .12 is converting to 0.12 but I want to avoid that
The following code will convert the string array values into decimals and arrange them in descending order and again I have to print it as string, not decimals. The problem here is while converting the strings to decimals the ".1" value is changing to "0.1", but I need it to print that as ".1" only.
Code:
import java.math.BigDecimal;
import java.util.*;
class Solution{
public static void main(String []args){
//Input
Scanner sc= new Scanner(System.in);
int n=sc.nextInt();
String []s=new String[n+2];
for(int i=0;i<n;i++){
s[i]=sc.next();
}
sc.close();
BigDecimal[] d=new BigDecimal[n];
for(int i=0;i<n;i++){
d[i]=new BigDecimal(s[i]);
}
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
if(d[j].compareTo(d[i]) == 0)
continue;
else if(d[j].compareTo(d[i]) > 0)
{
BigDecimal t=d[i];
d[i]=d[j];
d[j]=t;
}
}
}
for(int i=0;i<n;i++)
{
s[i]=d[i].toString();
}
//Output
for(int i=0;i<n;i++)
{
System.out.println(s[i]);
}
}
}
Input:
9
-100
50
0
56.6
90
0.12
.12
02.34
000.000
Expected Output:
90
56.6
50
02.34
0.12
.12
0
000.000
-100
My Output:
90
56.6
50
2.34
0.12
0.12
0
0.000
-100
Solution 1:
You have to create a class where you save both String
and double
values. When you compare items for sorting, you should use double
value. When you print items, you should use String
value.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
scan.useLocale(Locale.ENGLISH);
StringDoubleNumber[] numbers = readStringNumbers(scan);
Arrays.sort(numbers);
printDesc(numbers);
}
private static StringDoubleNumber[] readStringNumbers(Scanner scan) {
System.out.print("Total numbers: ");
int total = scan.nextInt();
StringDoubleNumber[] numbers = new StringDoubleNumber[total];
for (int i = 0; i < total; i++) {
System.out.format("%d: ", i + 1);
numbers[i] = new StringDoubleNumber(scan.next());
}
return numbers;
}
private static void printDesc(StringDoubleNumber[] numbers) {
System.out.println("Numbers in descending order:");
for (int i = numbers.length - 1; i >= 0; i--)
System.out.println(numbers[i]);
}
private static final class StringDoubleNumber implements Comparable<StringDoubleNumber> {
private final String str;
private final double val;
public StringDoubleNumber(String str) {
this.str = str;
val = Double.parseDouble(str);
}
@Override
public int compareTo(StringDoubleNumber obj) {
return Double.compare(val, obj.val);
}
@Override
public String toString() {
return str;
}
}