简体   繁体   English

如何通过Eclipse控制台运行Java代码?

[英]How to run java code through eclipse console?

I have virtually no java/eclipse experience, so bear with me. 我几乎没有Java / Eclipse的经验,请耐心等待。 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? 我将如何在Eclipse控制台中对其进行测试以确保其正常运行? 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. 例如,如果我使用的是python,我对此有一些经验,所以我认为只需将gcd(32,24)键入IDLE并按Enter。

Java is a compiled language, not a scripting language. Java是一种编译语言,而不是脚本语言。 There is no console with read-eval-print loop. 没有具有read-eval-print循环的控制台。 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. 您可以使用System.in以便在控制台中键入内容,然后按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. 另一种选择是简单地使用main方法。 You start a java application from within a main method. 您可以从main方法中启动Java应用程序。 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: 因此,例如在Eclipse中,您可以右键单击包含main方法的文件,然后选择Run as -> Java Application ,它将从您的main方法运行代码:

public static void main(String[] args) {

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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