Home > Blockchain >  how to make a method that divides the integer of the parameter with 2? (new to java)
how to make a method that divides the integer of the parameter with 2? (new to java)

Time:11-21

Im supposed to write a method divideByTwo that takes an integer as a parameter and returns the number divided by 2. and i need to try to solve the problem with a single program statement in the method. I don't know how to fix the problem, i've used modulo, while loop, changed the return value but still don't know what i am doing wrong. Any kind of help appreciated!

this is what i've done so far:

public static int divideByTwo(int a){
    
    
    
 
    
    int i = 0;
    
    while(i < 1){
        System.out.print(a/2);
        i  ;
        
        
    }
     return a;   

}

expected output

CodePudding user response:

The reason why you are getting 51 when you're entering 10 in the example is because it prints 10/2 = 5 and then it returns i which is 1. Then you are printing the method with parameter 10 which prints 5 in the method and then 1 as the return value. If you just want to divide the number by two, then all you need to write in the method is return a/2; and then just print the method divideByTwo(a);.

CodePudding user response:

You are out-thinking yourself. The method has a simple purpose - divide the value provided by 2 and return that result.

  • remove the print statement - there is nothing to print
  • remove the loop and loop variable - there is nothing to loop over

That leaves you with...

public static int divideByTwo(int a) {
  return a;
}

... but we don't want a - we want a divided by 2. You did the division in your print statement so do that division in the return statement and you are done.

public static int divideByTwo(int a) {
  return a/2;
}

The answer was in you all along!

  • Related