如何在两个输出之间添加空格?

13

这是我正在使用的代码。

public void displayCustomerInfo() {
    System.out.println(Name + Income);
}

我使用一个单独的主方法来调用上面的方法:

first.displayCustomerInfo();
second.displayCustomerInfo();
third.displayCustomerInfo();

有没有一种简单的方法在输出之间轻松添加空格?目前的样子是这样的:

Jaden100000.0
Angela70000.0
Bob10000.0
7个回答

23

添加一个空格或制表符:

public void displayCustomerInfo() {
    System.out.println(Name + " " + Income);

    // or a tab
    System.out.println(Name + "\t" + Income);
}

22
你可以按照以下方式使用System.out.printf()来获得漂亮的格式化输出
System.out.printf("%-20s %s\n", Name, Income);

打印输出结果如下:

Jaden             100000.0
Angela            70000.0
Bob               10000.0

这种格式的意思是:

%-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

您还可以为Income参数添加格式,以便按所需方式打印数字。

请参阅此处获得快速参考。


有关安卓的任何问题吗?如何在安卓中执行相同的操作? - Krishna Ch

3
System.out.println(Name + " " + Income);

这是您的意思吗?这将在名称和收入之间添加一个空格吗?

2

这样可以吗?

 System.out.println(Name + " " + Income);

0

可以在打印命令中添加 +"\n" ,以在下一行显示代码块。

例如,System.out.println("a" + "\n" + "b") 将在第一行输出 a,第二行输出 b。


0

代码:

class Main
{
    public static void main(String[] args)  
    {
        int a=10, b=20;
        System.out.println(a + " " + b);
    }
}

输入: 无

输出: 10 20


-1
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 );
   }
}

能详细说明一下吗? - RamenChef
1
当然可以。System.out.println(x+ " " +y ); - Fajla Rabby

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接