Latest :

Return the Next Number from the Integer Passed In Java

Return the Next Number from the Integer Passed in Java, for a given problem, we must first understand the problem statement thoroughly and observe if any constraints are given in the problem. Following this, we should determine the inputs required to solve the problem.

Also, we should also decide on what our expected output would be. Finally, we determine the logic to be used to arrive at this expected output.

Our problem statement here is, to find the next number of the given integer. For this, we require an input integer whose next value is to be found. Our expected output would be the next integer for the given number.

Firstly, to read our input integer at runtime, we can make use of a well known class in Java called the Scanner class.

This can be used to read any primitive datatype input like int, float, double, string, etc., at the runtime.

To make use of this class, we must initially create an object instantiating it and by using this object, we can invoke any desired method based on our input type. Here, our input is an integer hence, we invoke the nextInt() method as follows:

After reading this input, we call a static method (next) and pass this integer input (n) as its argument. This static method (next) executes its set of statements and returns an integer which is the next integer of the given argument.

static int next(int n)

The solution is very simple. We just have to increment the argument by 1 using the pre-increment (++n) operation and then return this value to the main method. pre-increment operator increments its operand value by 1 before executing the statement.

return ++n;

This is our resultant output value which can then be displayed on the console screen by using a System.out method called println(). This method displays its contents and then, end at a new line every time.

System.out.println(“Next number (“+n+”) is:”+next(n));

Output – 1:

Output – 2:


Check Also

Convert String To Date In Java – JavaTutoring

Convert String to Date In Java – Here we cover the different ways to convert ...