简体   繁体   中英

Printing negative values in Java

My variables are

float amountLeft, amount;
char v1;

My goal is to let the user know If he uses more than a $1000 he will be in debt, the user can keep purchasing but he will be in debt. I can't get my head around negative numbers. How would I keep track of the negative numbers? For example: "You just went over your limit. You owe us -5$ "

If you want to take a look at my code here it is.

 amountLeft = 1000.0f;
    while(amountLeft > 0) {
      System.out.println(String.format("%3s %,1.2f %3s", "You have"  , amountLeft, "money remaining to spend."));
      System.out.println("Enter the cost of the item you want buy");
    amount = new Scanner(System.in).nextFloat();
      System.out.println("are you sure you wanna purchase this item?");
      v1 = keyboard.next().charAt(0);
      if (v1 == 'y')
      {
        amountLeft = amountLeft - amount;
        System.out.printf("%.2f",amountLeft);

You can to create a situation that allows that user to spend if he is negative if (amountleft < 0)

Also, that loop should be while (amount >= 0) because the user won't owe anything if he is at 0 dollars.

Simply add a new statement inside your amount left:

if (amountLeft < 0) {
   // alert user that hes over the amount
}

Add this at the end of your code, and then you can print his negative amount every type the loop is executed.

You can then print the amount as per normal.

Variables can start at positive, and end at negative, or go from positive, to negative, to positive with no dramas.

Let me paraphrase your question. You want to let the user buy stuff even though his/her money is not enough. And each time he/she does that, you print "you owe us $xxx". But now you are printing "you owe us $-xxx". You basically want the negative number to be printed out as a positive number, right?

The other answers tell you how to check for negative value but you are actually asking how to print negative values as positive ones.

There is a method for this in the java.lang.Math class! You can print -5 as a positive number this way:

System.out.println ("You owe us $" + Math.abs(amountLeft));

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