简体   繁体   English

如何在终端中运行Java代码

[英]How to run java code in terminal

How do i run this piece of code? 我如何运行这段代码? It's a clicker. 这是一个答题器。

public class Counter{

    private int value;

    public Counter(int initialValue){
        value = initialValue;
    }
    public void click(){
        value = value + 1;
    }
    public int getValue(){
        return value;
    }
}

I'm running osX and i want this 'executed' in the terminal. 我正在运行osX,我希望在终端中“执行”。 The file (Counter.java) is placed on the desktop, therefor the first thing i do in the terminal is 文件(Counter.java)放置在桌面上,因此我在终端上做的第一件事是

cd desktop
javac Counter.java

After this i want to call click, but i'm not sure how to. 在此之后,我想打电话给click,但是我不确定该怎么做。 I tried 'java Counter.click()' but it gives me the error: -bash: syntax error near unexpected token `(' . 我尝试了'java Counter.click()',但它给了我错误:-bash:意外标记'('附近的语法错误。

This is a very noobish question, sorry :) 这是一个非常讨厌的问题,对不起:)

You just created a class Counter . 您刚刚创建了一个Counter类。 To run this class you must make another class Launcher.java or something and add 要运行此类,您必须创建另一个类Launcher.java或其他内容并添加

public static void main(String[] args) {
    // create Clicker here
}

In this function, you create a object of Counter 在此函数中,创建一个Counter对象

Counter counter = new Counter(0);

Then you can execute member-function on this new Counter object: 然后,您可以在此新的Counter对象上执行成员函数:

 counter.click();

If you would want to add some userinput, i suggest you take a look at JOptionPane ex. 如果您想添加一些用户输入,我建议您看看JOptionPane ex。 You could do something like this: 您可以执行以下操作:

public static void main(String[] args) {
        String choice="";
        Counter counter= new Counter(0);
        do{
           choice = JOptionPane.showInputDialog("message");
           switch (choice) {
            case click:
            counter.click();
            break;
                case getValue:
            JOptionPane.showMessageDialog(null,counter.getValue());
            break;
        default:
            break;
        }  
        }while(!choice.equals("close");      
    }

then export your project as a RUNNABLE jar. 然后将您的项目导出为RUNNABLE jar。

ps. PS。 JOptionPane is just one solution, Google is your friend ! JOptionPane只是一种解决方案,Google是您的朋友!

您不能调用诸如Counter.click()之类的成员方法,在其中使用main方法,然后尝试以

$java Counter

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

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