繁体   English   中英

简单的Java代码中的某些错误

[英]Some Error in a simple java code

这是一个简单的Java代码,无需使用任何String API函数即可反转一个String,但是在最后一行中,当它打印反转的字符串时,输出语句(System.out.println())中存在一些问题

这是代码:

class StringReverse
{
    public static void main(String[] args) throws java.io.IOException
    {
        int str[] = new int[100];
        int i=0,j;
        System.out.println("Enter a string");
        while(true)
        {
            str[i]=System.in.read();
            if(str[i++]==13)
                break;
        }
        String reversed="",simple = new String(str,0,i-1);
        System.out.println(simple);

        // now reversing the string
        for(j=i-1;j>=0;j--)
            reversed+=((char)str[j]);
        System.out.println("String is "+reversed);
    }
}

样本输出为 在此处输入图片说明

这是因为您正在Windows上运行。 当您按Enter键时 ,将传输两个特殊字符- <CR>\\r<LF>\\n * 您正在捕获\\n ,并停止阅读。 但是, \\r保留在缓冲区中,并成为反向字符串的第一个字符。 这就是为什么反转的字符串会打印在"String is "输出的顶部。

这是逐步进行的最终结果:

  • 打印"String is " 光标在位置编号十(从零开始)
  • 反向字符串"gagan\\r"的第一个字符被打印出来。 字符是不可见的,但是光标的位置变为零; 光标停留在同一行
  • 反转的字符串"nagag"会打印在"String is ""String is ""String is " "Strin"部分上
  • 现在您将看到输出"nagagg is"

* <CR>代表“回车”; <LF>代表“换行”。

另外,除了使用不需要的代码行之外,您还可以使用StringBuilder来简单地做到这一点。 有关StringBuilder的更多信息,请访问: ClassStringBuilder-Oracle

下面是使用StringBuilder的实现。

import java.lang.StringBuilder;
import java.util.Scanner;

public class ReverseString{
    public static void main(String[] args){
        //String s = getString("Please enter a string");
        //you can either pass the getString directly into the constructor of 
        //StringBuilder or first instanciated and pass that String.
        StringBuilder rev = new StringBuilder(getString("Please enter a String"));
        //A build-in method of the StringBuilder class that reverses a StringBuilder.
        StringBuilder k = rev.reverse();
        //A cmd print
        print("The reverse is: "+k);
    }

    public static String getString(String msg) {
        Scanner in = new Scanner(System.in);
        print(msg);
        String s = in.nextLine();
        return s;
    }

    public static void print(String s) {
        System.out.println(s);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM