GCD input number

0 votes
asked Dec 8, 2014 by the-new-guy

I would need help to where i can manually add the input numbers within the script. If you see that a= 273 and b=108 I would like that to print the actually GCD but I am not actually getting the correct input. I am doing something simple but it is still not working. Also would this put in absolute terms, meaning if i put a negative will it make it a positive.

Edit: I am not trying to use a scanner class.

public class Divisor 
{
    private static int a;
    private static int b;
    {
    a= 273;
    b=108;
    }
    private static int returnNumber(int a, int b) {
        if (b == 0) {
            return a;
        }
        return returnNumber(b, a % b);
    }

    public static void main(String[] args) {

        System.out.println(returnNumber(a, b));
    }
}

1 Answer

+2 votes
answered Dec 8, 2014 by rendon

You could use Scanner from java.util, e.g.

    Scanner scanner = new Scanner(System.in);
    int a = scanner.nextInt();
    int b = scanner.nextInt();
    System.out.println(a + " " + b);

Or BufferedReader from java.io:

    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    int a = Integer.parseInt(reader.readLine());
    int b = Integer.parseInt(reader.readLine());
    System.out.println(a + " " + b);

The previous snippet assumes each number is in a different line.

BTW, it's a good idea to put these lines inside a try-catch block with IOException.

EDIT: As @musical_coder mention, you can also use command line arguments, here is an example:

    int a = Integer.parseInt(args[0]);
    int b = Integer.parseInt(args[1]);
    System.out.println(a + " " + b);

In this case you should run you program with:

$ java Divisor <first number> <second number>
Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter

...