在java中查找正确的返回类型

时间:2016-02-25 01:31:31

标签: java methods try-catch return-type

我无法做出正确的退货程序。我想将第一个参数指定的金额类型的当前总数增加第二个参数中指定的金额。我遇到了一些问题。请帮帮我。

public void newValue(char amountType, double amount)
{
  if (amount <=0) // if amount entered is invalid
    throw new IllegalArgumentException("The amount needs to be 0 or larger "+amountType+" "+amount);

  if (amountType !='T' || amountType !='D' || amountType !='E') // if letter for the amount type is invalid (T,D, or E)
  totalTicketSales += amount;
  totalMoneyDonated += amount;
  totalExpenses += amount;

  throw new IllegalArgumentException("That is an invalid letter value. "+amountType+" "+amount
            + "The data will be ignored"); 

    currentAmount = amountType + amount;  //this is where my issue is
}

所以这是最新的。我试图根据您的反馈对此进行一些更改。

public double newValue(char amountType, double amount)
{
    double currentAmount = amountType + amount; 

  if (amount <=0) // if amount entered is invalid
  //I get an error here on this exception
    throw new IllegalArgumentException("The amount needs to be 0 or larger "+amountType+" "+amount);


  if (amountType !='T' || amountType !='D' || amountType !='E') // if letter for the amount type is invalid (T,D, or E)
  {
      totalTicketSales += amount;
  totalMoneyDonated += amount;
  totalExpenses += amount;

  throw new IllegalArgumentException("That is an invalid letter value. "+amountType+" "+amount
            + "The data will be ignored"); 
  }
     return currentAmount;
}

1 个答案:

答案 0 :(得分:0)

  1. Java中的if语法是:

    array_walk

    如果您只有一个句子,则不需要括号,但如果if语句中有多行,则需要将它们括在括号中。因此,您需要将第二个括在括号中:

    if (Statement) {
        sentence1;
        sentence2;
        ...
    }
    
  2. 此外,您正在为char添加double。这是不可能做到的。

    if (amountType !='T' || amountType !='D' || amountType !='E') // if letter for the amount type is invalid (T,D, or E)
    {    
        totalTicketSales += amount;
        totalMoneyDonated += amount;
        totalExpenses += amount;
    
        throw new IllegalArgumentException("That is an invalid letter value. " + amountType + " "+ amount + "The data will be ignored"); 
    }
    
  3. 您在方法中返回“无”。 Void方法意味着你不会返回任何东西。如果要返回double变量,则需要将yout方法标题更改为:

    currentAmount = amountType + amount;  // YOU CAN'T ADD A DOUBLE TO A CHAR
    
  4. 这是一个向initialValue添加金额的代码示例。如果opType是T,D或E,那么它会抛出异常(基于您发布的代码)。

    public double newValue(char amountType, double amount){
        code;
        ...
    }