help me with my syntax (Java)

Status
Not open for further replies.

turo

Wise, Aged Ars Veteran
178
I'm trying to make a simple program that "beeps" ever 45 seconds, 11 times. I don't see why my program won't compile. Please help:
code:<HR>
Code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.Timer;<P>public class Workout
{
	private AudioClip bonk;
        public Timer timer;
	
	public void init()
	{
		bonk = getAudioClip (getCodeBase(), "imsend.wav");
		
		for (int i=0; i<12;i++)
		{
		timer = new Timer (45000, bonk.play());
		timer.start();
		}
	}	
}

thx,
Kobayashi
 

Paralis

Ars Scholae Palatinae
930
The compiler messages would be helpful, but to take a blind guess:

You're instantiating timer each time you run the loop. Generally speaking, Java doesn't like this. It should run the same if you put the instantiation before the loop, and only re-iterate the method call.

edit: AudioClip is an interface of java.applet. Add that to your import line, and it should compile fine.
 

gaev

Wise, Aged Ars Veteran
145
Your problem is that the class you are writing does not extend "Applet" nor does it have a "public static void main()" function. The way you have it set up with the "public void init()" it should be a java applet and therefore the class should extend "Applet" like this:

code:<HR>
Code:
import java.applet.*;<P>public class Workout extends Applet
{
...
}
 

Paralis

Ars Scholae Palatinae
930
The first two things I said apply. You're reinstantiating the timer object 12 times, which really isn't necessary.

And it doesn't know what AudioClip is because you didn't include the class java.applet.

The class also is not defined as an applet: it doesn't extend any applet class, so it's inferred that it extends Object. It will by default try to run a main(), which doesn't exist.

Timer, further, won't except a method-call parameter--it seems only to take 'this', which refers to the actionPerformed method. If you put your loop in there, it should run--on my box it compiles and runs without error, but without a sound-file included I can't tell if it's doing anything. Anyway, this code compiles, and should do what you want:

code:<HR>
Code:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.Timer;<P>public class Workout2 extends Applet implements ActionListener
{
   private AudioClip bonk;
   Timer timer;<P>   public void init()
   {<P>      bonk = getAudioClip(getCodeBase(), "imsend.wav");
      timer = new Timer(45000, this);<P>   }<P>   public void actionPerformed(ActionEvent actionEvent)
   {
      start();
   }<P>   public void start()
   {
      for (int i = 0; i < 12; i++)
        timer.start();
   }
}
 
Status
Not open for further replies.