java - 向后打印字符串

标签 java string

我正在尝试反向打印字符串。即

hello world 

应该显示为:

 dlrow olleh

但结果只显示第一个单词的相反。即

 olleh

有什么想法吗?

import java.util.Scanner;

public class test {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner input = new Scanner(System.in);

        System.out.println("Input a string:"); 
        String s;
        s = input.next();

        String original, reverse = "";

        original = s;

        int length = original.length();

        for ( int i = length - 1 ; i >= 0 ; i-- )
            reverse = reverse + original.charAt(i);

        System.out.println("Reverse of entered string is: "+reverse);
        input.close();  
    }
}

最佳答案

使用input.next()仅存储变量中的下一个单词(仅“hello”)。试试这个:

    System.out.println("Input a string:");
    String s;
    s = input.nextLine();

    System.out.println("entered: " + s);

关于java - 向后打印字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22430801/

相关文章:

java - Tomcat Servlet 路径

java - 谁能解释一下 java 是如何设计 HashMap 的 hash() 函数的?

Java 拒绝 ssl 证书,但 Firefox 接受它

java - Tomcat 7 中通过 XML 配置的域间 cookie

python - 从字符串到结果的计算公式

c - 如何告诉 C 编译器不要重叠我的字符串

perl - 在 Perl 中访问字符串中的单个字符时,是 substr 还是拆分为数组更快?

java - 如何进入 FutureTask 执行状态?

java - 何时以及如何有效地使用 StringBuilder/Buffer?

c# - 此代码是否依赖于字符串实习才能工作?