Home > Software design >  How do I reverse a number in Java using String?
How do I reverse a number in Java using String?

Time:11-20

I have used the below logic, but getting an exception "java.lang.StringIndexOutOfBoundsException". Help will be appreciated. Thank you!!

import java.util.Scanner;
public class Demo{

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number:- ");
        String number = sc.next();                      

        for (int i = number.length(); i >= 0; i--) {    
            System.out.println(number.charAt(i));
        }

    }

}

CodePudding user response:

You only need to iterate across the string halfway, swapping the characters as the indices go towards the middle. This works for even or odd length strings.

Scanner sc = new Scanner(System.in);
System.out.print("Enter a number:- ");
char[] chars = sc.next().toCharArray();
int len = chars.length;
for (int i = 0; i < len/2; i  ) {
     char c1 = chars[i];
     char c2 = chars[len-i-1];
     chars[i] = c2;
     chars[len-i-1] = c1;
}
String s = new String(chars);
System.out.println(s);

Or just use the reverse() method included in the StringBuilder class.

CodePudding user response:

import java.util.Scanner;
public class Demo{

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number:- ");
        String number = sc.next();                      

        for (int i = number.length() -1 ; i >= 0; i--) {    // correct answer: number.lenght() -1 as array start with 0.
            System.out.print(number.charAt(i)); //using print instead of println so that it display in same line
        }

    }

}
  • Related