【问题标题】:Java Concatenation of Strings Through CMD input通过 CMD 输入的 Java 字符串连接
【发布时间】:2014-12-19 00:02:06
【问题描述】:

所以我有两个类:

class ConcatTesting{
    public static void main(String args[]) throws java.io.IOException{
        char inLetter;
        String input="";

        //This loops takes line of cmd and makes the input variable into that string
        for(;;){
            inLetter=(char) System.in.read(); //get next char

            //if the line hasn't ended then add that char to input
            if(inLetter!='\n'){
                input+=String.valueOf(inLetter);
            }else{
                //other wise line has ended so input is finished
                break;
            }
        }

        //removes extra white-spaces
        input.trim();

        //test what input is to make sure it is working correctly
        System.out.println(input);

        //test concat function
        UseConcat.ask(input);

        UseConcat.ask("pie");
    }
}

class UseConcat{
    public static void ask(String str){
        System.out.println("What does " + str +" mean?");
    }
}

在程序中我调用了两次静态方法UseConcat.ask(String str)

UseConcat.ask(String str) 中的参数是input 变量时,连接似乎失败了。但是,当我调用 UseConcat.ask(String str) 并使用随机字符串参数时,串联工作。

input 变量是 cmd 转换为字符串的第一行写入。

这是一个示例图像。

如图所示,输入变量设置为WOA。

但是UseConcat.ask(input); 打印出mean?oes WOA intsead WOA 是什么意思?

当输入被打印时:System.out.println(input); 它会正常打印 WOA

另一方面,当我调用 UseConcat.ask("pie"); 时,它可以工作并打印:pie 是什么意思?

【问题讨论】:

  • 为什么不使用Scanner 来捕获用户输入?
  • @RyanJ 似乎可以与扫描仪一起使用,但为什么我目前的操作方式会失败?
  • 我可以告诉你这与终端的行为有关,而不是特定的代码。它使用带有终端仿真的 IDE 工作。我怀疑你被this post 所描述的东西所困扰。不过,我建议切换到 Scanner,因为它更强大,更符合当前的做法。

标签: java string input concatenation


【解决方案1】:

Windows 上的文本行(通常用于文件,但总是用于控制台窗口)以 两个 字符 CR(回车)和 LF(换行)结尾,它们(最容易)写成 \r\n 在 Java 中。您只删除 LF,然后输出“WOA{CR} 是什么意思?” {CR} 字符将光标移动到左边距并导致“意思?”部分覆盖“What d”部分。如果您没有丢弃结果,您的 input.trim() 会解决此问题。其他平台不同; Unix只用LF,AIUI MacOSX只用CR。

旨在处理Scanner 或更基本的BufferedReader.readLine() 等文本的Java 方法可以为您处理CR 和LF 的任意组合,在您的应用程序中使用更少的代码,并且更高效;反复执行 String += letter 对于长时间输入来说效率极低——尽管如果你只在控制台窗口中运行这个程序,这会将输入行限制在一些不是荒谬的巨大数量。

【讨论】:

    猜你喜欢
    • 2017-06-24
    • 1970-01-01
    • 1970-01-01
    • 2019-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-10
    • 1970-01-01
    相关资源
    最近更新 更多