Is there any point in including the "throws ArithmeticException" declaration in the divide method?
try
{
divide(10,0);
}
catch(ArithmeticException e)
{
System.out.println("Exception caught.");
}
}
public static void divide(int x, int y) throws ArithmeticException
{
int result = 0;
result = x / y;
System.out.println("Quotient is " + result);
return;
}
One of the reasons for it is to catch whether your division is done with the denominator as '0'. Anything that is divided by 0 is infinity. Your program won't be able to interpret the result and therefore an exception error will be thrown for the divide method.
ArithmeticException is only thrown when dividing by zero or when working with BigDecimal and not rounding. Since your divide method is working with the "int" data type I would just use an if statement that only allows you to do the division of y does not equal zero.
I noticed this is a void method and you are not doing anything other than printing the result. I am not sure if that is your intention but if you need the value you should consider rewriting this to fit your needs.
Related
*>printing 1 to a numbers without using if and while ,but this is not working in java
**class printOut{//class started here
static int PrintN(int x)
{
(x>1)?(System.out.println(PrintN(x--))):System.out.println(x);
//above code is recursively calling PrintN to print decreemented value
return 0;
}
public static void main(String args[])
{
int a=10;//initialized variable
PrintN(a);//calling the static method wihout creating its object
}
}***
//my question was to write a program to find out 1 to n numbers without using while or if loops.
Since you want to print, starting at 1, until reaching some initial input number, your logic should be to first make the recursive call, then print afterwards, on the way back. Something like this:
public static void printN(int x) {
if (x > 1) {
printN(x - 1);
}
System.out.println(x);
}
I don't think your recursive method has to return any value, because the number/state to be printed is passed along the method calls. Note also that the base case occurs when the number becomes 1. In this case, we don't make another recursive call, but rather just print ourself and then return to the higher caller.
Demo
//A method for find the smallest integer from the array, assuming
//that the array is not empty
public class SmallestIntegerFinder {
public static int findSmallestInt(int[] arrayOfIntegers) {
int smallest=0;
for(int i=0;i<arrayOfIntegers.length;i++){
if(smallest>arrayOfIntegers[i]) {
smallest=arrayOfIntegers[i];
}
}
return smallest;
}
}
//Junit test
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class SmallestIntegerFinderTest {
#Test
public void example1(){
int expected = 11;
int actual = SmallestIntegerFinder.findSmallestInt(new int[]{78,56,232,12,11,43});
assertEquals(expected, actual);
}
}
I have this annoying error. expected:<11> but was:<0> java.lang.AssertionError: expected:<11> but was:<0> what can I do? How do I sovle this error?? The code works well when i do not use JUnit. As soon as I include JUnit test I get errors. Please advise
The issue is that when you initialize smallest, you set it to 0, which is smaller than all of your test data, hence the 0 result.
A naive way of solving this would be to initially set smallest to some obscenely large constant, however this still may not work if you end up working with an even larger dataset. (Technically you could set it to the max integer value, but this is quite ugly)
A better solution would be to initialize the value of smallest to the first integer of your dataset, arrayOfIntegers[0]. By doing this, smallest is guaranteed to be at least as large as at least one item in your dataset.
If functions are borrowed from the mathematical concept of mapping a value from some set S onto T, then the function:
int increment(int input)
{
return input + 1;
}
would be the mapping from the integers onto the integers. And so the logic goes for most functions, but what about if the return value of a function is void. Does that still fit the mathematical paradigm, or is that a departure, or what is that?
Simple question here, when void follows a function in AS3 what is it doing?
public function sayGoodbye():void { trace("Goodbye from MySubClass");}
void type indicates to the compiler that the function you have written will not return any value, in the other side if you indicate other type T than void the compiler expect that you return T.
Ex:
function foo(a:int):int { // here the compiler expect that somewhere
// in your function you return an int
return a;
}
void means that it has no return value. I.e., you can't use it in an expression.
void specifies that the function will return no value, or, to be more exact, the special undefined value type. Note that the function return can be used in an expression and it is the unique value of the undefined type.
In actionscript 3 to conform to the strict mode you need to specify variable types and function return types in order for the compiler to know what types to expect and to optimize your application.
What does "Overloaded"/"Overload" mean in regards to programming?
It means that you are providing a function (method or operator) with the same name, but with a different signature.
For example:
void doSomething();
int doSomething(string x);
int doSomething(int a, int b, int c);
Basic Concept
Overloading, or "method overloading" is the name of the concept of having more than one methods with the same name but with different parameters.
For e.g. System.DateTime class in c# have more than one ToString method. The standard ToString uses the default culture of the system to convert the datetime to string:
new DateTime(2008, 11, 14).ToString(); // returns "14/11/2008" in America
while another overload of the same method allows the user to customize the format:
new DateTime(2008, 11, 14).ToString("dd MMM yyyy"); // returns "11 Nov 2008"
Sometimes parameter name may be the same but the parameter types may differ:
Convert.ToInt32(123m);
converts a decimal to int while
Convert.ToInt32("123");
converts a string to int.
Overload Resolution
For finding the best overload to call, compiler performs an operation named "overload resolution". For the first example, compiler can find the best method simply by matching the argument count. For the second example, compiler automatically calls the decimal version of replace method if you pass a decimal parameter and calls string version if you pass a string parameter. From the list of possible outputs, if compiler cannot find a suitable one to call, you will get a compiler error like "The best overload does not match the parameters...".
You can find lots of information on how different compilers perform overload resolution.
A function is overloaded when it has more than one signature. This means that you can call it with different argument types. For instance, you may have a function for printing a variable on screen, and you can define it for different argument types:
void print(int i);
void print(char i);
void print(UserDefinedType t);
In this case, the function print() would have three overloads.
It means having different versions of the same function which take different types of parameters. Such a function is "overloaded". For example, take the following function:
void Print(std::string str) {
std::cout << str << endl;
}
You can use this function to print a string to the screen. However, this function cannot be used when you want to print an integer, you can then make a second version of the function, like this:
void Print(int i) {
std::cout << i << endl;
}
Now the function is overloaded, and which version of the function will be called depends on the parameters you give it.
Others have answered what an overload is. When you are starting out it gets confused with override/overriding.
As opposed to overloading, overriding is defining a method with the same signature in the subclass (or child class), which overrides the parent classes implementation. Some language require explicit directive, such as virtual member function in C++ or override in Delphi and C#.
using System;
public class DrawingObject
{
public virtual void Draw()
{
Console.WriteLine("I'm just a generic drawing object.");
}
}
public class Line : DrawingObject
{
public override void Draw()
{
Console.WriteLine("I'm a Line.");
}
}
An overloaded method is one with several options for the number and type of parameters. For instance:
foo(foo)
foo(foo, bar)
both would do relatively the same thing but one has a second parameter for more options
Also you can have the same method take different types
int Convert(int i)
int Convert(double i)
int Convert(float i)
Just like in common usage, it refers to something (in this case, a method name), doing more than one job.
Overloading is the poor man's version of multimethods from CLOS and other languages. It's the confusing one.
Overriding is the usual OO one. It goes with inheritance, we call it redefinition too (e.g. in https://stackoverflow.com/users/3827/eed3si9n's answer Line provides a specialized definition of Draw().