Click here to Skip to main content
13,705,353 members
Rate this:
 
Please Sign up or sign in to vote.
See more:
I'm trying to reverse a string of numbers and input comma without Number format class.

When a number like 1000 is inputted the output will be

0,0,0,1

Instead of

000,1

What I have tried:

String num=JOptionPane.showInputDialog("enter number");
    Int length=num.length()-1;
    String res="";
    Char ch;

    //For numbers with thousands
    If(length<=6){
       for(int k=length; k>=0; k--){
              ch=num.chartAt(k);
              res+=ch;
              if(ch==num.chartAt(2)){
                    res+=",";
              }
        }
    }
    System.out.println(res);
Posted 14-Nov-17 1:50am
Updated 14-Nov-17 10:32am
v2
Comments
Kenneth Haugland 14-Nov-17 8:17am
   
https://stackoverflow.com/questions/12678781/reversing-an-array-in-java
CPallini 14-Nov-17 8:31am
   
It is not clear what are you trying to achieve. Could you make an example with input, expected output and observed output (ouy actually did, but not in a clear way, at least in my opinion)?
Drekel 14-Nov-17 10:02am
   
The expected output should be 000,1 but I'm getting 0,0,0,1
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

Try this:
int integer = 1000;
String string = Integer.toString(integer);
String reverseString = new StringBuffer(string).reverse().toString();
String [] splitArray = reverseString.split("");
String finalResult = String.join(",", splitArray);
System.out.println(finalResult);
  Permalink  
Comments
Mehdi Gholam 14-Nov-17 8:32am
   
My 5!
Peter Leow 15-Nov-17 1:12am
   
Thank you, Mehdi Gholam.
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 2

It should be
String num=JOptionPane.showInputDialog("enter number");
    int length=num.length()-1;
    String res="";
    char ch;

    //For numbers with thousands
    if(length<=6){
       for(int k=length; k>=0; k--){
              ch=num.charAt(k);
              res+=ch;
              if(k==1)
                    res+=",";
        }
    }
    System.out.println(res);
  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Cookies | Terms of Service
Web04-2016 | 2.8.180920.1 | Last Updated 14 Nov 2017
Copyright © CodeProject, 1999-2018
All Rights Reserved.
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100