0

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

3
  • I should add that i'm, obviously, very new to java. Commented Nov 21, 2014 at 16:40
  • Then added to the question ! Not as a comment Commented Nov 21, 2014 at 16:41
  • 1
    You obviously need to go and read the basic tutorials. Commented Nov 21, 2014 at 16:41

2 Answers 2

3

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 !

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

Comments

1

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

$java Counter

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.