开发者

How to create a mutator method that adds together two numbers then displays a message

开发者 https://www.devze.com 2022-12-19 09:45 出处:网络
How do I create a mutator method that adds two numbers but if the added number that is entered is negative, it will display an error message and not change the first number. Suggestions please.

How do I create a mutator method that adds two numbers but if the added number that is entered is negative, it will display an error message and not change the first number. Suggestions please.

  public void restock(int newStockQuantity)
  {
    if(newStockQuantity < 0)
        {
            stockQ = stoc开发者_如何转开发kQ;
        }
        {
            system.out.println("Error not negative numbers");
        }
    else 
        {  
            stockQ = stockQ + newStockQuantity;    
        }
  }     


Well, for one thing you don't need the

stockQ = stockQ;

statement - that doesn't do anything.

Next is the problem of having multiple blocks in the "if" statement. If you did want to keep the no-op assignment, you could change your method to:

public void restock(int newStockQuantity)
{
    if(newStockQuantity < 0)
    {
        stockQ = stockQ;
        System.out.println("Error not negative numbers");
    }
    else 
    {  
        stockQ = stockQ + newStockQuantity;    
    }
}

With the no-op assignment removed, it's just:

public void restock(int newStockQuantity)
{
    if(newStockQuantity < 0)
    {
        System.out.println("Error not negative numbers");
    }
    else 
    {  
        stockQ = stockQ + newStockQuantity;    
    }
}

Note the change from "system" to "System" as well - Java is case-sensitive.

That should compile and work.

Personally I would suggest throwing an exception if the method has an invalid argument instead of printing out a message to the console, but obviously it depends on the situation.

If you don't understand my first comment about having multiple blocks for the if statement, then I'd suggest going back to a good introductory Java book, and look at the syntax of if statements. It's slightly unclear which point you were having trouble with.


IMHO the best approach is the exception. Another point is to output the offending value, so a user of the method knows what the error is about. It also reveals errors in your check ;). Third point is to check for invariants first, bailing out with an exception or some appliable return-statement.

public void restock(int newStockQuantity) {
  if(newStockQuantity < 0) {
    throw new IllegalArgumentException("new stock " + newStockQuantity " must not be negative");
  }
  if (newStockQuantity == 0)
  {
     // nothing necessary, probably worth another exception?
     return;
  }
  stockQ = stockQ + newStockQuantity;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消