[Solved] How do I use a function involving integers?


Think of it like passing functions in math. The GCDFunction() has to receive the numbers into the function so we do

public static void GCDFunction(int num1, int num2)

That also lets Java know the type it is, type int. And your java variables are scoped inside of the functions so you have to print the output in the function that created the variable in your scenario.

So once you have that function set up to receive the variables and output after processing, you call the function in the main with a

GCDFunction(num1, num2);

Where num1 and num2 are the variables that have your integers stored in.

The end result after a little rearranging looks like this.

import java.util.Scanner;

public class GCDFunctionJavaProgram {

public static void main(String[] args) {

    int num1;
    int num2;

    Scanner input = new Scanner(System.in);

    System.out.print("Enter your first number: ");
    num1 = input.nextInt();
    System.out.print("Enter your second number: ");
    num2 = input.nextInt();

    GCDFunction(num1, num2);

}

public static void GCDFunction(int num1, int num2) {
    int div;
    if(num1 > num2){
       div = num2;
    }

   else{ div = num1;}

   while((num1 % div!= 0)||(num2 % div != 0))
   {
   div --;
   }//end of while loop
   System.out.printf("The GCD is %d ", div);
   }

3

solved How do I use a function involving integers?