Search code examples
javastringjava.util.scannerstring-formatting

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


I am trying to make a ticket program. Here is my code:

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

It asks me how many people, then it prints something very different than what I want it to print. If I were to type 4 people this is what will come out.

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

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

I want it to print (The 4 is the input I put in)

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

Solution

  • You see an extra newline because of:

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

    println() will produce a newline. The \n produce a second newline, hence pushing down the line 2 times.

    There is no need to use print printf and println. Just do:

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