Display line number in console? Java

时间:2015-12-10 01:45:37

标签: java console

I am trying to output my withdrawal/deposit transactions to the console, which works perfectly. But I would like to output them with the line number next to the card number.

My code is:

public synchronized int withdraw(int cardId, int amount) {

    bankBalance = bankBalance - amount;
    System.out.printf("%-12s%-12s%-12s%-12s\n","line(" + cardId + ")", amount," ", + bankBalance);
    return bankBalance;
       }

public synchronized int deposit(int cardId, int amount) {

    bankBalance = bankBalance + amount;
    System.out.printf("%-12s%-12s%-12s%-12s\n","line(" + cardId + ")", " " , amount, + bankBalance);

    return bankBalance;
}

Which will output like so:

Transaction Withdrawal  Deposit     Balance     
____________________________________________
line(3)                 5           15          
line(5)                 2           17          
line(2)     6                       11  

The number in brackets is relating to the card number which is good I want to leave that there. I also want to have the line number which just loops like 1,2,3,4,5,6,7,8,9 where the text "line" is like this:

Transaction Withdrawal  Deposit     Balance     
____________________________________________
1(3)                     5           15          
2(5)                     2           17          
3(2)        6                       11  

Any ideas?

2 个答案:

答案 0 :(得分:-1)

Based on the synchronized modifiers you are using, you'll need a counter that won't run into concurrency issues. Maybe you could try this:

private static final AtomicInteger i = new AtomicInteger();

public synchronized int withdraw(int cardId, int amount) {
    bankBalance = bankBalance - amount;
    System.out.printf("%-12s%-12s%-12s%-12s\n", i.incrementAndGet() + "(" + cardId + ")", amount," ", + bankBalance);
    return bankBalance;
       }

public synchronized int deposit(int cardId, int amount) {

    bankBalance = bankBalance + amount;
    System.out.printf("%-12s%-12s%-12s%-12s\n", i.incrementAndGet() + "(" + cardId + ")", " " , amount, + bankBalance);

    return bankBalance;
}

答案 1 :(得分:-2)

You want to increment lineNumber.

int lineNumber;

lineNumber++;

System.out.println("Random print statement" +lineNumber)

lineNumber++;

System.out.println("LineNumber has been increased by one" +lineNumber)

enter image description here

Let me know if this solved your problem!

:-)