0

I have virtually no java/eclipse experience, so bear with me. I have written a code to use the Euclidean algorithm to compute a greatest common divisor.

public class Euclid {
    public static int gcd(int a, int b){
        while (b!= 0){
            if (a > b){
                a -= b;
            }
            else {
                b -= a;
            }
        }
        return a;
    }

}

How would I go about testing this in the eclipse console to ensure that it runs properly? E.g were I using python, which I have some experience with, I'd think to simply type gcd(32, 24) into IDLE and hit enter.

1
  • 2
    Write a main method, and put some prints in it. Java is not an interpreted language so things like "IDLE" do not exist. But for small programs, compilation is pretty quick and this will give you the fastest results. Commented Jan 26, 2015 at 22:52

2 Answers 2

1

Java is a compiled language, not a scripting language. There is no console with read-eval-print loop. You can add a main function in the class:

public static void main (String [] args){ System.out.println(gcd(32,24)); }

And then you can right click and run

Sign up to request clarification or add additional context in comments.

Comments

0

You can use System.in so you can type something into the console and press enter. After you've done that, you can work with the input as shown in the following example:

public static void main(String[] args) {

    System.out.println("Enter something here : ");

    try{
        BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
        String s = bufferRead.readLine();

        System.out.println(s);
    }
    catch(IOException e)
    {
        e.printStackTrace();
    }

  }

Another option is simply using the main method. You start a java application from within a main method. So for example in Eclipse you can just right-click the file with the main method in it and choose Run as -> Java Application and it will run your code from your main method:

public static void main(String[] args) {

        Euclid euclid = new Euclid();
        int value = euclid.gcd(32, 24);

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.