十进制格式导致'此处不允许使用void类型'错误

时间:2016-01-22 00:04:22

标签: java void decimalformat

在我的toString方法中,我的所有变量都打印正常,我的所有代码都没有问题。

我需要编辑以更改小数格式,以便不是我的数字打印1E9或其他(更长的浮点数),它实际上会打印非科学记数法版本(123,456,789.00)。

所以在我的toString方法中,我初始化了一个DecimalFormat对象并将其实现为我的值。

在我没有收到关于"' void'这里不允许输入"但是在实现十进制格式之后,它现在给了我正在尝试打印的所有其他3个变量的错误。

为什么我的小数格式会影响其他变量?

import java.text.DecimalFormat;

public class Project {  
  String projName;        //Name of a project
  int projNumber;      //Number of a project
  String projLocation;    //Location of a project
  Budget projBudget;      //Budget of a project

public Project(double amount) {
  this.projName = "?";
  this.projNumber = 0;
  this.projLocation = "?";
  Budget thisBudget = new Budget(amount);
  this.projBudget = thisBudget;
}

public String getName(){
  return projName;
}

public int getNumber() {
  return projNumber;
}

public String getLocation() {
  return projLocation;
}

public Budget getBudget() {
  return projBudget;
}

public void setName(String aName) {
  projName = aName;
}

public void setNumber(int aNumber) {
  projNumber = aNumber;
}

public void setLocation(String aLocation) {
  projLocation = aLocation;
}

public boolean addExpenditure(double amount) {
  return projBudget.addSpending(amount);
}

public String toString() {
  String format = "###,###.##";
  DecimalFormat decimalFormat = new DecimalFormat(format);
  return "\nProject Name:\t\t" + getName() + "\nProject Number:\t\t" + getNumber() + "\nProject Location:\t\t" + getLocation() + "\nBudget:\nInitial Funding\t$" + decimalFormat.applyPattern(String.valueOf(projBudget.initialFunding)) + "\nSpending\t\t$" + decimalFormat.applyPattern(String.valueOf(projBudget.spending)) + "\nCurrent Balance\t$" + decimalFormat.applyPattern(String.valueOf(projBudget.currentBalance)) +"\n\n";
}
}

1 个答案:

答案 0 :(得分:1)

因为decimalFormat.applyPattern()输出类型无效

你可以使用decimalFormat.format( value )方法,它的输出是String 所以你可以毫无困难地在你的toString方法中使用它。