如何在Java中使用String反转数字?

mmvthczy  于 2022-11-20  发布在  Java
关注(0)|答案(2)|浏览(110)

我已经使用了下面的逻辑,但是得到了一个异常“java.lang.StringIndexOutOfBoundsException”。帮助将不胜感激。谢谢!!

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));
        }

    }

}
esyap4oy

esyap4oy1#

你只需要遍历字符串的一半,当索引向中间移动时交换字符,这对偶数或奇数长度的字符串都有效。

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);

或者只使用StringBuilder类中包含的reverse()方法。

6jygbczu

6jygbczu2#

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
        }

    }

}

相关问题