Sultenhest
Sultenhest

Reputation: 49

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. The file (Counter.java) is placed on the desktop, therefor the first thing i do in the terminal is

cd desktop
javac Counter.java

After this i want to call click, but i'm not sure how to. I tried 'java Counter.click()' but it gives me the error: -bash: syntax error near unexpected token `(' .

This is a very noobish question, sorry :)

Upvotes: 0

Views: 228

Answers (2)

MrMe TumbsUp
MrMe TumbsUp

Reputation: 416

You just created a class Counter. To run this class you must make another class Launcher.java or something and add

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

In this function, you create a object of Counter

Counter counter = new Counter(0);

Then you can execute member-function on this new Counter object:

 counter.click();

If you would want to add some userinput, i suggest you take a look at 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.

ps. JOptionPane is just one solution, Google is your friend !

Upvotes: 3

Isuru Madusanka
Isuru Madusanka

Reputation: 373

You cant call member methods like Counter.click() use main method in it and then try to run as

$java Counter

Upvotes: 1

Related Questions