Java 如何在两个输出之间添加空格?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19393202/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I add a space in between two outputs?
提问by cbass0
This is the code I am working with.
这是我正在使用的代码。
public void displayCustomerInfo() {
System.out.println(Name + Income);
}
I use a separate main method with this code to call the method above:
我使用带有此代码的单独 main 方法来调用上面的方法:
first.displayCustomerInfo();
second.displayCustomerInfo();
third.displayCustomerInfo();
Is there a way to easily add spaces between the outputs? This is what it currently looks like:
有没有办法在输出之间轻松添加空格?这是它目前的样子:
Jaden100000.0
Angela70000.0
Bob10000.0
采纳答案by hexacyanide
Add a literal space, or a tab:
添加文字空格或制表符:
public void displayCustomerInfo() {
System.out.println(Name + " " + Income);
// or a tab
System.out.println(Name + "\t" + Income);
}
回答by Scott Solmer
Like this?
像这样?
System.out.println(Name + " " + Income);
回答by justin henricks
System.out.println(Name + " " + Income);
Is that what you mean? That will put a space between the name and the income?
你是这个意思吗?那会在姓名和收入之间留一个空格吗?
回答by Java Devil
You can use System.out.printf()
like this if you want to get nicely formatted
System.out.printf()
如果你想得到很好的格式,你可以这样使用
System.out.printf("%-20s %s\n", Name, Income);
Prints like:
打印如下:
Jaden 100000.0
Angela 70000.0
Bob 10000.0
This format means:
这种格式意味着:
%-20s -> this is the first argument, Name, left justified and padded to 20 spaces.
%s -> this is the second argument, Income, if income is a decimal swap with %f
\n -> new line character
You could also add formatting to the Income argument so that the number is printed as desired
您还可以向 Income 参数添加格式,以便根据需要打印数字
Check out this for a quick reference
查看此内容以获取快速参考
回答by Fajla Rabby
import java.util.Scanner;
public class class2 {
public void Multipleclass(){
String x,y;
Scanner sc=new Scanner(System.in);
System.out.println("Enter your First name");
x=sc.next();
System.out.println("Enter your Last name");
y=sc.next();
System.out.println(x+ " " +y );
}
}
回答by Pankaj
+"\n" + can be added in print command to display the code block after it in next line
+"\n" + 可以在打印命令中添加以在下一行显示其后的代码块
E.g. System.out.println ("a" + "\n" + "b") outputs a in first line and b in second line.
例如 System.out.println ("a" + "\n" + "b") 在第一行输出 a,在第二行输出 b。