简体   繁体   English

用Java打印负值

[英]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. 我的目标是让用户知道,如果他使用了超过$ 1000的债务,则用户可以继续购买,但仍将负债。 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$ " 例如:“您刚刚超过了限额。您欠我们-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) 您可以创建一种情况,如果该用户为负数if (amountleft < 0) ,则允许该用户花费

Also, that loop should be while (amount >= 0) because the user won't owe anything if he is at 0 dollars. 另外,该循环应为while (amount >= 0)因为如果用户的价格为0美元,则他不会欠任何东西。

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". 并且每次他/她这样做时,您都会打印“您欠我们$ xxx”。 But now you are printing "you owe us $-xxx". 但是现在您正在打印“您欠我们$ -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! java.lang.Math类中有一个用于此目的的方法! You can print -5 as a positive number this way: 您可以通过以下方式将-5打印为正数:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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