遇到变量未打印和\n 不工作的问题

Having trouble with variable not getting printed and \n not working

我正在尝试制作票务程序。这是我的代码:

public class CODE {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        System.out.println("How many people? ");
        int people = input.nextInt();
        int cost =(int) (2.50*people);
        int x=0;

        System.out.println("---------------------- \n");
        System.out.printf("People:",people,"\n");
        System.out.printf("Total cost:$",cost,"\n");
        System.out.println("---------------------- \n");
    }
}

它问我有多少人,然后打印出一些与我想要打印的非常不同的东西。如果我输入 4 个人,这就是结果。

How many people? 
4
---------------------- 

People:Total cost:$---------------------- 

我要打印(4是我输入的)

How many people?
4
---------------------- 
People:4
Total cost:
---------------------- 

您看到一个额外的换行符是因为:

System.out.println("---------------------- \n");

println() 将产生一个换行符。 \n 产生第二个换行符,因此将行向下推 2 次。

不需要使用打印printfprintln。只要做:

System.out.println("----------------------);
System.out.println("People:" + people);
System.out.println("Total cost:$" + cost);
System.out.println("----------------------);

在您的 Printf 中,您需要为变量放置一个占位符。

System.out.printf("People: %d" ,people);
System.out.printf("Total cost:$ %d", cost);

其中 %dint 的占位符。

或者您也可以这样做:

System.out.println("People: " + people);
System.out.println("Total cost: $" + cost);

阅读更多关于 printf here