简体   繁体   中英

How to run java code through eclipse console?

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? Eg were I using python, which I have some experience with, I'd think to simply type gcd(32, 24) into IDLE and hit enter.

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

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);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM