有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

缺少货币计算java的返回语句

它说我缺少一个返回语句,无法确定需要返回什么。任何帮助将不胜感激,详细信息,这是我的CSC200课程的第一个java程序

Money.java:23: error: missing return statement
    }
    ^
1 error

我的代码:

public class Money
{
    // declare class variables
    double total; // used to store the Money value as a double precision floating point number like 34.2
    // you will need more variables declared here to handle each of the currency types; for example int hundreds to keep track of how many hundred dollar bills
    int hundreds;
    // this one will help you print floating point values in US currency format like $10.50
    NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US);

    // convert current currency values to a string
    public String toString()
    {

    }

    // converts amount to US currency format
    public String toCurrency(double amount)
    {
      return nf.format(Math.round(amount * 100.0) / 100.0);
    }

    // convert currency to float
    // read currency values from Scanner s and compute value
    // output results
    public void processChange(Scanner s)
    {
    }

完整错误: image


共 (2) 个答案

  1. # 1 楼答案

    void processChange()方法不同,String tostring()方法需要String作为返回值,但该方法没有返回语句。 比如说,如果你写了什么要归还的东西

    public String toString(){
       return total + hundreds + "";//return a String
    }
    

    或者,如果不需要执行此方法,则可以抛出异常

    public String toString(){
       throw new NotSupportedException();//the method is not supported
    }
    

    如果确实需要一个toString()方法,而不需要为totalhundreds的不同值返回不同的字符串,请使用transient关键字声明它们:

    transient double total;//will not be serialised.
    transient int hundreds;//will not be serialised.
    
    public String toString(){
       return "";//return an empty String
    }
    
  2. # 2 楼答案

    方法toString为空,但它声明返回类型为String的对象

        public String toString()
        {
    
        }
    

    可以使用此方法返回有关Money对象当前状态的消息。在这种情况下,我建议使用以下行填充此方法:

        return "total: " + total + ", hundreds: " + hundreds;
    

    例如,如果您尝试使用System.out.println(...);输出此对象,您将获得有关此对象包含的每个值的信息