在Java zybooks中添加空格
这是我现在拥有的:
import java.util.Scanner;
public class Welcome {
public static void main(String[] args) {
// Complete this statement to create a new instance of Scanner passing in System.in
Scanner scan = new Scanner(System.in);
// Complete this statement to use the scanner object to read a string from the user
String user_name = scan.next();
// Add the statement to print the desired output
System.out.println("Hello" + user_name + "and welcome to CS Online!");
}
}
如果用户名=乔,则输出:HelloDoeand欢迎来到CS Online! 我通过在“ Hello”之后放置一个空间和“这样:
System.ou.println("Hello " + user name + " and welcome to CS Online!");
我的问题是,有更好的方法可以在变量和字符串之间添加空格?我做的方式是,我的问题是我的修复吗?这似乎不是很好的做法。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
system.out.printf
(立即打印)或string.format
(返回在string
)中,可以仅使用单个字符串
带有占位符值,该值被变量代替,%s
是String
变量的占位符。当您拥有要在
String
内打印的多个变量时,这可能特别有用。请注意,我还将
user_name
更改为用户名
在您询问良好实践时,请遵循适当的Java命名骆驼命名约定。这是一个具有多个变量的示例:
You can use
System.out.printf
(immediately prints) orString.format
(returns result in aString
) instead which lets you use only a singleString
with a placeholder value that gets replaced by a variable,%s
is the placeholder for aString
variable.This can be especially useful when you have multiple variables you want to print inside of a
String
.Note that I also changed
user_name
touserName
to follow proper Java naming conventions of camelCasing as you were asking about good practices.Here is an example with multiple variables:
我不知道为什么应该是不好的做法。我的意思是,这是您想要的 - 有两个空间,一个又一个“你好”,一个之前的“和”,但实际上有更好的方法可以实现这一目标。通过使用格式,您只需一个带有一个参数的字符串。
I don't know about why it should be bad practise. I mean that's litteraly what you want - to have two spaces, one after "Hello" and one before "and", but there is, in fact, better way to achive this. By using formating you'll have only one string with one parameter.