【发布时间】: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