简体   繁体   中英

Display line number in console? Java

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?

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

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)

在此处输入图片说明

Let me know if this solved your problem!

:-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM