为什么在$符号前打印负号?

时间:2014-04-07 22:11:20

标签: java string

我应该在banckAccount类中添加一个toString方法。

它应该返回一个用逗号和空格分隔的名称。 Ex: "Yana"以及余额3.03,调用yana.toString()应返回字符串"Yana, $3.03"

我试图添加:

public String toString() {
    return  name + ", " + "$"+ balance;
}

当我输入时它起作用:

"user, $90.01" 

但是当我进入

"Bankrupt Government, -$765432.10"

我一直在:

 "Bankrupt Government, $-765432.1"      

代码:

import java.util.*;

public class BankAccount {

     String name;
     double balance;

     public void deposit (double amount ){
          balance = balance + amount;


     }

     public void withdraw ( double amount) {
          balance = balance - amount ;          
     }

  }//end of class

4 个答案:

答案 0 :(得分:3)

您的余额为负值,因此会按列出的方式打印。它必须是

if(balance < 0){
   balance = balance * -1;
   return  name + ", " + "-$"+ balance;
}
else{
  return  name + ", " + "$"+ balance;
}

答案 1 :(得分:3)

你的答案就在这里:

return  name + ", " + "$"+ balance;

Java简单地将字符串连接起来,就像你定义它一样。因此,如果balance为负数,您将获得$,后跟负数。

如果您希望它在适当的位置显示-,您可以执行以下操作:

String sign = (balance < 0) ? "-" : "";
System.out.println(name + ", " + sign + "$" + Math.abs(balance));

答案 2 :(得分:0)

很明显,你的方法toString()正在做什么。如果余额为负数,则只需将其添加到字符串中,使用&#34; - &#34;在&#34; $&#34;之后签名。如果余额是积极的,我会发现:

private String toString() { if (balance > 0.0) { return name + ", " + "$" + balance; } else { return name + ", -$" + (balance * (-1)); } }

或者

private String toString() { return name + ", " + balance > 0.0 ? ("$" + balance) : ("-$" + (balance * (-1))); }

答案 3 :(得分:0)

希望这有助于运行此程序

      import java.util.*;
      import java.io.*;
      public class HelloWorld{
      public String toString() {
        if(balance<0)
        {
            balance= Math.abs(balance);
             return  name + ", " +"-"+ "$"+ balance;
        }else
        {
    return  name + ", " + "$"+ balance;
        }
}
       String name="sachin";
     double balance=-1000.00;
 public void deposit (double amount ){
          balance = balance + amount;


     }
      public void withdraw ( double amount) {
          balance = balance - amount ;          
     }
     public static void main(String []args){
       // System.out.println("Hello World");

            HelloWorld helloWorld = new HelloWorld();

         System.out.println(helloWorld.toString());

     }
}