Help...Why won't this compile?
Why won't this compile?
Here is my code:
import java.util.Calendar;
import javax.swing.JOptionPane;
public class GetAge{
public static void main(String[] args){
int month=Integer.parseInt(JOptionPane.showInputDialog
(null,"Enter what month(MM) you were born:"));
int day=Integer.parseInt(JOptionPane.showInputDialog
(null,"Enter what day(dd) you were born:"));
int year=Integer.parseInt(JOptionPane.showInputDialog
(null,"Enter what year(yyyy) you were born:"));
Calendar rightNow = Calendar.getInstance();
int year2 = rightNow.get(Calendar.YEAR);
int day2 = rightNow.get(Calendar.DATE);
int month2 = rightNow.get(Calendar.MONTH)+1;
int years = year2-year-1;
int months = month2-month+12;
if(day2 >= day)
int days = day2-day;
else
days = day-day2+8;
JOptionPane.showMessageDialog(null,"You are: " + years
+ " years " + months + " months and " + days + " days old.");
}
What you're doing is using days after the if statement; without curly braces only a valid statement is allowed.
But if you add curly braces, days will be available only in the if block.
So what you should do is:
import java.util.Calendar;
import javax.swing.JOptionPane;
public class GetAge{
public static void main(String[] args){
int month=Integer.parseInt(JOptionPane.showInputDialog
(null,"Enter what month(MM) you were born:"));
int day=Integer.parseInt(JOptionPane.showInputDialog
(null,"Enter what day(dd) you were born:"));
int year=Integer.parseInt(JOptionPane.showInputDialog
(null,"Enter what year(yyyy) you were born:"));
Calendar rightNow = Calendar.getInstance();
int year2 = rightNow.get(Calendar.YEAR);
int day2 = rightNow.get(Calendar.DATE);
int month2 = rightNow.get(Calendar.MONTH)+1;
int years = year2-year-1;
int months = month2-month+12;
int days = 0; //declare here
if(day2 >= day)
days = day2-day; //...and use here
else
days = day-day2+8; //..and here
JOptionPane.showMessageDialog(null,"You are: " + years
+ " years " + months + " months and " + days + " days old.");
}
Similar Messages
-
HELP-Why won't this function return a value
I want to get this XML data OUT of the function, but it just
won't work. What I am doing wrong??? Tracing "xmlList" gives me the
output i want IN the function, but if I can't get it OUT. If i set
the function to "String", I still can't get the function to return
a value or anyway to get this data OUT of the function. Please
help.
var xml:XML;
var xmlList:XMLList;
var xmlLoader:URLLoader = new URLLoader;
xmlLoader.load(new URLRequest("data/imagesT.xml"));
xmlLoader.addEventListener(Event.COMPLETE, xmlLoaded);
function xmlLoaded(event:Event):String
xml = XML(event.target.data);
xmlList = xml.children()[0].child(2);It won't though. Tracing xmlList outside (i.e. after it runs)
the function produces null with the function set to void. Inside
the function tracing producing the correct data. -
Why won't this compile ?
CREATE OR REPLACE FUNCTION FN0003_GetDisabilityCode
RETURN CHAR(8);
IS
DisabilityCode CHAR(8);
BEGIN
DisabilityCode := '00000000';
RETURN DisabilityCode;
END FN0003_GetDisabilityCode;Same as parameters, return datatype can't have length/precision and get rid of semi-colon. Change it to:
CREATE OR REPLACE FUNCTION FN0003_GetDisabilityCode
RETURN CHAR
IS
DisabilityCode CHAR(8);
BEGIN
DisabilityCode := '00000000';
RETURN DisabilityCode;
END FN0003_GetDisabilityCode;
SY. -
I'm trying to put these functions into a Loop to conserve
space. Why won't this work?
.Yeah, sly one is right. You can not have the "i" inside the
onRollOver function, what you have to do is: As the movieClip class
is dynamic you can create a property of the movieClip which stores
the value if the "i". And then, inside the onRollOver function, you
have to make reference to that property.
for (i=0; i<2; i++) {
this.regArray
.iterator = i;
this.regArray.onRollOver = function () {
showRegion(regArray[this.iterator]);
this.regArray
.onRollOut = function () {
hideRegion(regArray[this.iterator]); -
I purchased the new gen 7 ipod nano and needed to update itunes to 10.7 but my current software says its up to date and won't download 10.6.8 Currently I have 10.5.8 Why won't this update?
The first generation Intel-based Mac's were released in January 2006.
Snow Leopard requires an Intel processor:
General requirements
Mac computer with an Intel processor
1GB of memory
5GB of available disk space
DVD drive for installation
Some features require a compatible Internet service provider; fees may apply.
If you go to the Apple menu & "About this Mac" this will tell you what type of processor you have: -
Why won't this song play even after I authorized the computer? It says that I need to authorize the computer, then I enter my username and password and it says the computer is already authorized. But then the song still won't play. What do I do?
Use the Apple ID support -> http://www.apple.com/support/appleid/ - click through the contact information and select the iTunes, etc., hot button. You can have Apple call you or email them.
Clinton -
Why won't this code work?
All I want to do is resize the select panel to the same size as east panel. Why won't it work?
Space.java_____________________________________________
import javax.sound.sampled.*;
import java.awt.*;
import javax.sound.midi.*;
import javax.swing.*;
import java.util.*;
import java.awt.event.*;
import java.io.*;
public class Space extends JFrame implements ActionListener, Runnable{
//Sound
Sequence currentSound;
Sequencer player;
Thread soundCheck;
boolean check = true;
public void start(){
soundCheck = new Thread();
soundCheck.start();
public void run(){
try{
File bgsound = new File("Sounds" + File.separator + "Space.mid");
currentSound = MidiSystem.getSequence(bgsound);
player = MidiSystem.getSequencer();
player.open();
player.setSequence(currentSound);
player.start();
checkSound();
} catch (Exception exc){}
public void checkSound(){
while(check){
if(!player.isRunning()){
run();
try{
soundCheck.sleep((player.getMicrosecondLength() / 1000)-player.getMicrosecondPosition()); // sleep for the length of the track
}catch (InterruptedException IE){}
//Screen Variables:
Dimension SCREEN = Toolkit.getDefaultToolkit().getScreenSize();
final int SCREENWIDTH = SCREEN.width;
final int SCREENHEIGHT = SCREEN.height;
//Panels:
JPanel select, main, north, south, east;
//Buttons:
JButton instructB, cheatB, playB, exit, about;
//Labels:
JLabel open, cheat1, cheat2, cheatInstruct, i1, i2 , i3, aboutLabel;
//The container and frame:
static Space jframe;
Container content;
//The Constructor:
public Space(){
super("Space");
//set container attributes:
content = getContentPane();
content.setLayout(new BorderLayout());
//init panels:
main = new JPanel();
select = new JPanel();
north = new JPanel();
east = new JPanel();
south = new JPanel();
//set panel attributes:
select.setLayout(new GridLayout(3,0,10,10));
select.setBackground(Color.black);
main.setBackground(Color.black);
north.setBackground(Color.black);
//add panels:
content.add("West", select);
content.add("Center", main);
content.add("North", north);
content.add("East", east);
//Image Icons:
Icon exit1 = new ImageIcon("Images" + File.separator + "exit1.gif");
Icon exit2 = new ImageIcon("Images" + File.separator + "exit2.gif");
Icon about1 = new ImageIcon("Images" + File.separator + "about1.gif");
Icon about2 = new ImageIcon("Images" + File.separator + "about2.gif");
//init buttons, add their listeners, and set their attributes:
instructB = new JButton("Instructions", new ImageIcon("Images" + File.separator + "ship.gif"));
instructB.setContentAreaFilled(false);
instructB.setForeground(Color.yellow);
instructB.addActionListener(this);
select.add(instructB);
cheatB = new JButton("Cheats", new ImageIcon("Images" + File.separator + "cheat.gif"));
cheatB.setContentAreaFilled(false);
cheatB.setForeground(Color.yellow);
cheatB.addActionListener(this);
select.add(cheatB);
playB = new JButton("Play", new ImageIcon("Images" + File.separator + "ship2.gif"));
playB.setContentAreaFilled(false);
playB.setForeground(Color.yellow);
playB.addActionListener(this);
select.add(playB);
exit = new JButton();
exit.setRolloverEnabled(true);
exit.setIcon(exit1);
exit.setRolloverIcon(exit2);
exit.setBorderPainted(false);
exit.setContentAreaFilled(false);
exit.addActionListener(this);
north.add(exit);
about = new JButton();
about.setRolloverEnabled(true);
about.setIcon(about1);
about.setRolloverIcon(about2);
about.setBorderPainted(false);
about.setContentAreaFilled(false);
about.addActionListener(this);
north.add(about);
//Labels:
open = new JLabel("", new ImageIcon("Images" + File.separator + "open.gif"), JLabel.CENTER);
main.add(open);
cheat1 = new JLabel("<html><h1>tport</h1></html>");
cheat1.setForeground(Color.red);
cheat2 = new JLabel("<html><h1>zap</h1></html>");
cheat2.setForeground(Color.green);
cheatInstruct = new JLabel("<html><h1>Type a cheat at any time during a game, and press the \"Enter\" key.</html></h1>");
cheatInstruct.setForeground(Color.blue);
i1 = new JLabel("<html><h1>The arrow keys move your ship.</h1></html>");
i1.setForeground(Color.red);
i2 = new JLabel("<html><h1>The space-bar fires the gun.</h1></html>");
i2.setForeground(Color.green);
i3 = new JLabel("<html><h1>The red circles give upgrades.</html></h1>");
i3.setForeground(Color.blue);
aboutLabel = new JLabel("", new ImageIcon("Images" + File.separator + "aboutImage.gif"), JLabel.CENTER);
//centerPanel();
private void centerPanel(final int width, final int height){
try{
Runnable setPanelSize = new Runnable(){
public void run(){
east.setPreferredSize(new Dimension(width, height));
SwingUtilities.invokeAndWait(setPanelSize);
} catch (Exception e){}
public void actionPerformed(ActionEvent e){
//if the play button was pressed do:
if(e.getSource() == playB){
//do something
//else if the cheat button was pressed do:
else if(e.getSource() == cheatB){
//remove and add components
main.removeAll();
main.setLayout(new GridLayout(3,0,0,0));
main.add(cheat1);
main.add(cheat2);
main.add(cheatInstruct);
main.repaint();
main.validate();
else if(e.getSource() == instructB){
//remove and add components
main.removeAll();
main.setLayout(new GridLayout(3,0,0,0));
main.add(i1);
main.add(i2);
main.add(i3);
main.repaint();
main.validate();
else if(e.getSource() == exit){
jframe.setVisible(false);
showCredits();
else if(e.getSource() == about){
main.removeAll();
main.setLayout(new FlowLayout());
main.add(aboutLabel);
main.repaint();
main.validate();
public void showCredits(){
try{
String[] args = {};
Credits.main(args);
}catch (Exception e){}
public static void main(String args[]){
jframe = new Space();
jframe.setUndecorated(true);
jframe.setBounds(0, 0, jframe.SCREENWIDTH, jframe.SCREENHEIGHT);
jframe.setVisible(true);
jframe.show();
jframe.setResizable(false);
jframe.setDefaultCloseOperation(EXIT_ON_CLOSE);
jframe.centerPanel(jframe.select.getWidth(), jframe.select.getHeight());
jframe.run(); //start music
}The reason it wasn't working was because you were calling the method after you had set the frame visible, so you saw no change. On top of that, jframe.select.getWidth() only works after the frame is visible in this case. So it's best to set a fixed size for one of them, then use getWidth, or as I did... it's the same thing. I also changed the centerPanel method, I'm not sure if all that's exactly needed, but you can change it back if you think you'll need it.
import javax.sound.sampled.*;
import java.awt.*;
import javax.sound.midi.*;
import javax.swing.*;
import java.util.*;
import java.awt.event.*;
import java.io.*;
public class Space extends JFrame implements ActionListener, Runnable{
//Sound
Sequence currentSound;
Sequencer player;
Thread soundCheck;
boolean check = true;
public void start(){
soundCheck = new Thread();
soundCheck.start();
public void run(){
try{
File bgsound = new File("Sounds" + File.separator + "Space.mid");
currentSound = MidiSystem.getSequence(bgsound);
player = MidiSystem.getSequencer();
player.open();
player.setSequence(currentSound);
player.start();
checkSound();
} catch (Exception exc){}
public void checkSound(){
while(check){
if(!player.isRunning()){
run();
try{
soundCheck.sleep((player.getMicrosecondLength() / 1000)-player.getMicrosecondPosition()); // sleep for the length of the track
}catch (InterruptedException IE){}
//Screen Variables:
Dimension SCREEN = Toolkit.getDefaultToolkit().getScreenSize();
final int SCREENWIDTH = SCREEN.width;
final int SCREENHEIGHT = SCREEN.height;
//Panels:
JPanel select, main, north, south, east;
//Buttons:
JButton instructB, cheatB, playB, exit, about;
//Labels:
JLabel open, cheat1, cheat2, cheatInstruct, i1, i2 , i3, aboutLabel;
//The container and frame:
static Space jframe;
Container content;
//The Constructor:
public Space(){
super("Space");
//set container attributes:
content = getContentPane();
content.setLayout(new BorderLayout());
//init panels:
main = new JPanel();
select = new JPanel();
north = new JPanel();
east = new JPanel();
south = new JPanel();
//set panel attributes:
select.setLayout(new GridLayout(3,0,10,10));
select.setBackground(Color.black);
main.setBackground(Color.black);
north.setBackground(Color.black);
//add panels:
content.add("West", select);
content.add("Center", main);
content.add("North", north);
content.add("East", east);
//Image Icons:
Icon exit1 = new ImageIcon("Images" + File.separator + "exit1.gif");
Icon exit2 = new ImageIcon("Images" + File.separator + "exit2.gif");
Icon about1 = new ImageIcon("Images" + File.separator + "about1.gif");
Icon about2 = new ImageIcon("Images" + File.separator + "about2.gif");
//init buttons, add their listeners, and set their attributes:
instructB = new JButton("Instructions", new ImageIcon("Images" + File.separator + "ship.gif"));
instructB.setContentAreaFilled(false);
instructB.setForeground(Color.yellow);
instructB.addActionListener(this);
select.add(instructB);
cheatB = new JButton("Cheats", new ImageIcon("Images" + File.separator + "cheat.gif"));
cheatB.setContentAreaFilled(false);
cheatB.setForeground(Color.yellow);
cheatB.addActionListener(this);
select.add(cheatB);
playB = new JButton("Play", new ImageIcon("Images" + File.separator + "ship2.gif"));
playB.setContentAreaFilled(false);
playB.setForeground(Color.yellow);
playB.addActionListener(this);
select.add(playB);
exit = new JButton();
exit.setRolloverEnabled(true);
exit.setIcon(exit1);
exit.setRolloverIcon(exit2);
exit.setBorderPainted(false);
exit.setContentAreaFilled(false);
exit.addActionListener(this);
north.add(exit);
about = new JButton();
about.setRolloverEnabled(true);
about.setIcon(about1);
about.setRolloverIcon(about2);
about.setBorderPainted(false);
about.setContentAreaFilled(false);
about.addActionListener(this);
north.add(about);
//Labels:
open = new JLabel("", new ImageIcon("Images" + File.separator + "open.gif"), JLabel.CENTER);
main.add(open);
cheat1 = new JLabel("<html><h1>tport</h1></html>");
cheat1.setForeground(Color.red);
cheat2 = new JLabel("<html><h1>zap</h1></html>");
cheat2.setForeground(Color.green);
cheatInstruct = new JLabel("<html><h1>Type a cheat at any time during a game, and press the \"Enter\" key.</html></h1>");
cheatInstruct.setForeground(Color.blue);
i1 = new JLabel("<html><h1>The arrow keys move your ship.</h1></html>");
i1.setForeground(Color.red);
i2 = new JLabel("<html><h1>The space-bar fires the gun.</h1></html>");
i2.setForeground(Color.green);
i3 = new JLabel("<html><h1>The red circles give upgrades.</html></h1>");
i3.setForeground(Color.blue);
aboutLabel = new JLabel("", new ImageIcon("Images" + File.separator + "aboutImage.gif"), JLabel.CENTER);
east.setPreferredSize(new Dimension(125, SCREEN.width));
//centerPanel();
/*private void centerPanel(final int width, final int height){
try{
Runnable setPanelSize = new Runnable(){
public void run(){
east.setPreferredSize(new Dimension(width, height));
SwingUtilities.invokeAndWait(setPanelSize);
} catch (Exception e){}
private void centerPanel(final int width, final int height)
east.setPreferredSize(new Dimension(width, height));
public void actionPerformed(ActionEvent e){
//if the play button was pressed do:
if(e.getSource() == playB){
//do something
//else if the cheat button was pressed do:
else if(e.getSource() == cheatB){
//remove and add components
main.removeAll();
main.setLayout(new GridLayout(3,0,0,0));
main.add(cheat1);
main.add(cheat2);
main.add(cheatInstruct);
main.repaint();
main.validate();
else if(e.getSource() == instructB){
//remove and add components
main.removeAll();
main.setLayout(new GridLayout(3,0,0,0));
main.add(i1);
main.add(i2);
main.add(i3);
main.repaint();
main.validate();
else if(e.getSource() == exit){
jframe.setVisible(false);
//showCredits();
else if(e.getSource() == about){
main.removeAll();
main.setLayout(new FlowLayout());
main.add(aboutLabel);
main.repaint();
main.validate();
/*public void showCredits(){
try{
String[] args = {};
Credits.main(args);
}catch (Exception e){}
public static void main(String args[]){
jframe = new Space();
//jframe.centerPanel(500, jframe.select.getHeight());
jframe.setUndecorated(true);
jframe.setBounds(0, 0, jframe.SCREENWIDTH, jframe.SCREENHEIGHT);
jframe.setVisible(true);
jframe.show();
jframe.setResizable(false);
jframe.setDefaultCloseOperation(EXIT_ON_CLOSE);
//jframe.centerPanel(jframe.select.getWidth(), jframe.select.getHeight());
jframe.run(); //start music
}Sorry I lost all the indenting :) I guess you can take a look at the few lines I changed and copy those lines. -
Why won't this form submit?
Why won't the form on this page submit?
www.milesmemorials.com/contact.html
Php for this form is-
<?php
$name = $_POST['name'];
$visitor_email = $_POST['email'];
$message = $_POST['message'];
//Validate first
if(empty($name)||empty($visitor_email))
echo "Name and email are mandatory!";
exit;
if(IsInjected($visitor_email))
echo "Bad email value!";
exit;
$email_from = "milesmemorials.com";//<== update the email address
$email_subject = "Message from Miles Memorial contact form";
$email_body = "Visitors name: $name.\n".
"Message:\n $message".
$to = "[email protected]";//<== update the email address
$headers = 'From: '.$visitor_email."\r\n";
$headers .='Reply-To:'.$visitor_email."\r\n";
//Send the email!
mail($to,$email_subject,$email_body,$headers);
//done. redirect to thank-you page.
header('Location: thankyou.html');
// Function to validate against any email injection attempts
function IsInjected($str)
$injections = array('(\n+)',
'(\r+)',
'(\t+)',
'(%0A+)',
'(%0D+)',
'(%08+)',
'(%09+)'
$inject = join('|', $injections);
$inject = "/$inject/i";
if(preg_match($inject,$str))
return true;
else
return false;
?>>I do apologise if i seem slow, i am still very new to dreamweaver
Just to be clear, this is not an issue with learning dreamweaver. This is just a lack of understanding of HTML and PHP. You need to learn those first before trying to learn DW.
You have a form field named 'donorName' but are checking for a field named 'name'.
$name = $_POST['name'];
<input name="donerName" type="text"
You need to rename one or the other. -
Help why won't photoshop let me edit my photos anymore?
Why won't photoshop let me edit my photos I am a photographer and my photos need more editing but photoshop will open the tools but nothing happens with any of the tools!
Too little information …
Could you please post a screenshot with the pertinent Panels visible?
Boilerplate-text:
Are Photoshop and OS fully updated and have you performed the usual trouble-shooting routines (trashing prefs by keeping command-alt-shift/ctrl-alt-shift pressed while starting Photoshop after making sure all customized presets like Actions, Patterns, Brushes etc. have been saved and making a note of the Preferences you’ve changed, 3rd party plug-ins deactivation, system maintenance, cleaning caches, font validation, etc.)? -
Consolidate Library - why won't this work?
Hi there,
I've been using iTunes and my iPod on several iMacs successfully for years - I've just changed to a PC and now I feel like a beginner!
I can't seem to get iTunes for Windows to seek out all my MP3s and put them in iTunes. The only way I can get iTunes to put them in it's library is to play them - then iTunes recognises then and remebers them. I have tried clicking on consolidate library - nothing. I have tried downloading my new music directly into the iTunes music folder - nothing. I can maunally add the file I download music into, but I don't want to have to do that all the time.
Why won't iTunes just find my music for me? It does on my iMac!I dont know!
In what way is it not working? -
Why won't this slide show run it compiles
import java.awt.*;
import java.applet.*;
import java.net.*;
public class SlideShow extends Applet {
private Image[] images;
private String[] text;
private Label captions;
private volatile int curFrame;
private Thread timerThread;
private volatile boolean noStopRequested;
private boolean paused;
private final Object pauseLock = new Object();
public static void main( String[] args )
new SlideShow();
private void printThreadName(String prefix) {
String name = Thread.currentThread().getName();
System.out.println(prefix + name);
public void init() {
images = new Image[3];
text = new String[3];
captions = new Label();
setLayout(new BorderLayout());
add(BorderLayout.SOUTH, captions);
Label name = new Label("by Claude Monet");
name.setAlignment(Label.CENTER);
add(BorderLayout.EAST, name);
URL fig = null;
try {
fig = new URL("http://developer.java.sun.com:8080/" +
"developer/technicalArticles/Threads/applet/");
} catch (java.net.MalformedURLException ex) {
System.out.println("Bad URL");
return;
images[0] = getImage(fig, "bordighera.jpg");
images[1] = getImage(fig, "etretat.jpg");
images[2] = getImage(fig, "leyden.jpg");
text[0] = "Garden in Bordighera";
text[1] = "Rock Arch West of Etretat";
text[2] = "Bulbfield and Windmill near Leyden";
printThreadName("init is ");
startThread();
private void startThread() {
paused = true;
noStopRequested = true;
// Use this inner class to hide the public run method
Runnable r = new Runnable() {
public void run() {
runWork();
timerThread = new Thread(r, "Timer");
timerThread.start();
printThreadName("startThread is ");
private void stopThread() {
noStopRequested = false;
timerThread.interrupt();
printThreadName("stopThread is ");
private void runWork() { // note that this is private
printThreadName("run is ");
curFrame = 0;
try {
while ( noStopRequested ) {
waitWhilePaused();
curFrame = ( curFrame + 1 ) % images.length;
repaint();
Thread.sleep(3000);
} catch ( InterruptedException x ) {
// reassert interrupt
Thread.currentThread().interrupt();
System.out.println("interrupt and return from run");
private void setPaused(boolean newPauseState) {
synchronized ( pauseLock ) {
if ( paused != newPauseState ) {
paused = newPauseState;
pauseLock.notifyAll();
private void waitWhilePaused() throws InterruptedException {
synchronized ( pauseLock ) {
while ( paused ) {
pauseLock.wait();
public void paint(Graphics g) {
update(g);
printThreadName("paint is ");
public void update(Graphics g) {
g.drawImage(images[curFrame], 0, 0, this);
captions.setText(text[curFrame]);
printThreadName("update is ");
public void start() {
setPaused(false);
printThreadName("start is ");
public void stop() {
setPaused(true);
printThreadName("stop is ");
public void destroy() {
stopThread();
for (int i = 0; i < images.length; i++) {
images.flush();
images[i] = null;
text[i] = null;
images = null;
text = null;
printThreadName("destroy is ");w.r.t. the title of your topic: the set C of compilable programs is much
larger than the set R of programs that run correctly: |C| > |R|. This
is implies that at most n == |C|-|R| programs need some debugging.
The easiest form of debugging (oftenly overlooked) is System.out.println
which, when applied strategically, can do wonders: when two of those
printlns are inserted at point X and Y, and if at point X everything seems
to be correct while at point Y (later in time) everything seems to be rotten
to the bone, inserting another println at point (X+Y)/2 narrows down the
exact location of where the ugly bug hides from you.
kind regards,
Jos -
Why won't this Applet work? Any help?
I followed a tutorial, though the tutorial left me to do a lot of the work. Which is good.
Anyway, I finished the Applet, but I get a message in the bottom corner of the window saying "Applet not initialized."
I can't figure out what's wrong.
I downloaded the tutorial's source code and checked it, and I think I have everything they do... I tried running the downloaded source code and it worked fine.
Here's the main class file of my Applet:
import java.applet.*;
import java.awt.*;
import java.net.*;
public class Main2 extends Applet implements Runnable
AudioClip ballLost = getAudioClip(getCodeBase(), "beep_1.au");
AudioClip bounce = getAudioClip(getCodeBase(), "beep_2.au");
Player player = new Player();
Ball ball1 = new Ball(20, this.getSize().width+40, this.getSize().height-30,1,3,8,ballLost,bounce,player,Color.red);
Ball ball2 = new Ball(20, this.getSize().width+40, 30,1,5,10,ballLost,bounce,player,Color.blue);
Thread th;
Cursor c;
Image dbImage;
Graphics dbg;
boolean isStopped = true;
public void init()
c = new Cursor(Cursor.CROSSHAIR_CURSOR);
this.setCursor(c);
ballLost = getAudioClip(getCodeBase(), "beep_1.au");
bounce = getAudioClip(getCodeBase(), "beep_2.au");
player = new Player();
ball1 = new Ball(20, this.getSize().width+40, this.getSize().height-30,1,3,8,ballLost,bounce,player,Color.red);
ball2 = new Ball(20, this.getSize().width+40, 30,1,5,10,ballLost,bounce,player,Color.blue);
public void start()
th = new Thread(this);
th.start();
public void stop()
th.stop();
public void run()
Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
while (true)
if (player.getLives()>0 && !isStopped)
ball1.move();
ball2.move();
repaint();
try
Thread.sleep (30);
catch (InterruptedException ex)
// do nothing
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
public void paint(Graphics g)
if (player.getLives()>0)
ball1.drawBall(g);
ball2.drawBall(g);
if (isStopped)
g.setColor(Color.green);
g.drawString("Double click to start.", 40, 200);
else if (player.getLives() <= 0)
g.setColor(Color.green);
g.drawString("Game Over!", 40, 200);
g.drawString("Double click to player again", 40, 300);
isStopped = true;
public boolean mouseDown(Event e, int x, int y)
if (!isStopped)
if (ball1.userHit(x,y))
//Need audio
ball1.ballWasHit();
else if (ball2.userHit(x,y))
//Need audio
ball2.ballWasHit();
else
//Play normal shot audio
else if (isStopped && e.clickCount == 2)
isStopped = false;
init();
return true;
public void update (Graphics g)
if (dbImage == null)
dbImage = createImage (this.getSize().width, this.getSize().height);
dbg = dbImage.getGraphics ();
dbg.setColor (getBackground ());
dbg.fillRect (0, 0, this.getSize().width, this.getSize().height);
dbg.setColor (getForeground());
paint (dbg);
g.drawImage (dbImage, 0, 0, this);
}My HTML code uses <APPLET CODE="Main2.class" WIDTH=700 HEIGHT=400>.
And they are both located in the same folder.
Any idea what's going wrong here?
Thanks for any help.All of the files are in the folder.
My folder contains:
Main2.class
Ball.class
Player.class
ShooterGame.html
beep_1.au
beep_2.au
And corresponding source code files.
Looks correct, right?
... -
Why won't this source code compile?
I have been writing a simple app for a simple form. I have been using a gridbaglayout and checked compilation almost every step of the way, but then right as i am getting towards the end and have to start putting in the actioneventlisteners etc. ......... My code doesn't compile.
Here is the source code:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class LearnerLookup extends JFrame implements ActionListener {
void buildConstraints(GridBagConstraints gbc, int gx, int gy,
int gw, int gh, int wx, int wy) {
gbc.gridx = gx;
gbc.gridy = gy;
gbc.gridwidth = gw;
gbc.gridheight = gh;
gbc.weightx = wx;
gbc.weighty = wy;
/** Creates a new instance of LearnerLookup */
public LearnerLookup() {
super("Learner Lookup");
setBounds(225, 250, 300, 180);
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints constraints = new GridBagConstraints();
JPanel pane = new JPanel();
pane.setLayout(gridbag);
// Last Name Label
buildConstraints(constraints, 0, 0, 1, 1, 25, 25);
constraints.fill = GridBagConstraints.NONE;
constraints.anchor = GridBagConstraints.EAST;
JLabel lastNameLabel = new JLabel("Last Name:", JLabel.LEFT);
gridbag.setConstraints(lastNameLabel, constraints);
pane.add(lastNameLabel);
// Last Name Field
buildConstraints(constraints, 1, 0, 1, 1, 75, 0);
constraints.fill = GridBagConstraints.HORIZONTAL;
JTextField lastNameField = new JTextField(20);
gridbag.setConstraints(lastNameField, constraints);
pane.add(lastNameField);
// First Name Label
buildConstraints(constraints, 0, 1, 1, 1, 0, 25);
constraints.fill = GridBagConstraints.NONE;
constraints.anchor = GridBagConstraints.EAST;
JLabel firstNameLabel = new JLabel("First Name:", JLabel.LEFT);
gridbag.setConstraints(firstNameLabel, constraints);
pane.add(firstNameLabel);
//First Name Field
buildConstraints(constraints, 1, 1, 1, 1, 0, 0);
constraints.fill = GridBagConstraints.HORIZONTAL;
JTextField firstNameField = new JTextField(20);
gridbag.setConstraints(firstNameField, constraints);
pane.add(firstNameField);
// Admission Number Label
buildConstraints(constraints, 0, 2, 1, 1, 0, 25);
constraints.fill = GridBagConstraints.NONE;
constraints.anchor = GridBagConstraints.EAST;
JLabel admNumLabel = new JLabel("Admission Number:", JLabel.LEFT);
gridbag.setConstraints(admNumLabel, constraints);
pane.add(admNumLabel);
// Admission Number Field
buildConstraints(constraints, 1, 2, 1, 1, 0, 0);
constraints.fill = GridBagConstraints.HORIZONTAL;
JTextField admNumField = new JTextField(10);
gridbag.setConstraints(admNumField, constraints);
pane.add(admNumField);
// Enter Button
buildConstraints(constraints, 0, 3, 1, 1, 0, 15);
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.anchor = GridBagConstraints.SOUTHWEST;
JButton enterButton = new JButton("Enter");
gridbag.setConstraints(enterButton, constraints);
pane.add(enterButton);
// Clear Button
buildConstraints(constraints, 1, 3, 1, 1, 0, 0);
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.anchor = GridBagConstraints.SOUTHEAST;
JButton clearButton = new JButton("Clear");
gridbag.setConstraints(clearButton, constraints);
pane.add(clearButton);
//Content Pane
setContentPane(pane);
public static void main(String[] arguments) {
LearnerLookup lookup = new LearnerLookup();
ExitWindow exit = new ExitWindow();
lookup.addWindowListener(exit);
lookup.show();
public void actionPerformed(ActionEvent evt) {
Object source = evt.getSource();
if (source == enterButton);
The error message that I get is the following:
LearnerLookup.java [101:1] cannot resolve symbol
symbol : variable enterButton
location: class LearnerLookup
if (source == enterButton);
^
1 error
Errors compiling LearnerLookup.
I'd be glad for some enlightenment on this one.
ThanksenterButton is declared inside the constructor and so is not accessible from actionPerformed.
Declare enterButton as an instance variable and remove the declaration from the constructor.
e.g.public class LearnerLookup extends JFrame implements ActionListener {
JButton enterButton;and in constructor:
// JButton enterButton = new JButton("Enter"); Remove this line
enterButton = new JButton("Enter"); // replace with this. You'll probably need to do this for all the components with actionPerformed methods. -
I have four classes. I have been told that i can compile the main one and the rest will compile by them selves. This doesn't seem to work. I can't even compile then seperatley. Any ideas why they won't work?
Main Code;
public class TestBoundedBuffer {
public static void main(String args[] ) {
// just create the two threads and the bounded buffer
BoundedBuffer b = new BoundedBuffer();
ProduceIntegers p = new ProduceIntegers(b);
ConsumeIntegers c = new ConsumeIntegers(b);
p.start();
c.start();
THREE OTHER CLASSES:
public class BoundedBuffer {
private static final int BUFFER_SIZE = 5;
private int count, in, out;
private int [] buffer;
public BoundedBuffer() {
count = 0;
in = 0;
out = 0;
buffer = new int[BUFFER_SIZE];
public synchronized void enter(int item) {
while (count == BUFFER_SIZE) {
try {
wait();
catch (InterruptedException e) { }
// add an item to the buffer
count++;
buffer[in] = item;
in = (in + 1) % BUFFER_SIZE;
notify();
public synchronized int remove() {
int item;
while (count == 0) {
try {
wait();
catch (InterruptedException e) { }
// Remove an item from the buffer
count--;
item = buffer[out];
out = (out + 1) % BUFFER_SIZE;
notify();
return item;
NEXT CLASS:
public class ProduceIntegers extends Thread {
private BoundedBuffer buff;
public ProduceIntegers( BoundedBuffer b ) {
buff = b;
public void run() {
for (int i=0; i<100; i++) {
System.out.println("Produced " + i);
buff.enter(i);
NEXT CLASS:
public class ConsumeIntegers extends Thread {
private BoundedBuffer buff;
public ConsumeIntegers( BoundedBuffer b ) {
buff = b;
public void run() {
for (int i=0; i<100; i++) {
int item = buff.remove();
System.out.println( "Consumed " + item);1) each of the 4 classes needs to be written in their own .java file, and in the same directory as the main .java file
or
2) TestBoundedBuffer.java can contain all the code for the other 3 classes, but you have to remove "public" as the class accessor.
ie
public class ProduceIntegers extends Thread {
becomes
class ProduceIntegers extends Thread { -
Why won't this piece of code work?
Hello all, i am new to HTML and web design and i'm trying to make a website. I created this piece of code so that when the user mouses over one of the links (jpg image) it will change colors ( i have the same image in different color scheme saved in the same folder).
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>XXXXXXXXXX</title>
</head>
<body bgcolor="#000000">
<table width="1050" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td><table width="1050" border="0" cellspacing="0" cellpadding="0">
<tr>
<td><img src="_images/XXXXbanner.jpg" width="1050" height="311" alt="banner" /></td>
</tr>
</table>
<table width="901" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td width="150"><a href="index.html" onMouseOut="MM_swapImgRestore()" onMouseOver="MM_swapImage('ButtonOne','','_images/home_on.jpg',1)">
<img name="ButtonOne" border="0" src="_images/home.jpg" width="150" height="75" alt="home" /></a></td>
<td width="150"><a href="gallery.html" onMouseOut="MM_swapImgRestore()" onMouseOver="MM_swapImage('ButtonTwo','','_images/gallery_on.jpg',1)">
<img name="ButtonTwo" border="0" src="_images/gallery.jpg" width="150" height="75" alt="gallery" /></a></td>
<td width="150"><a href="products.html" onMouseOut="MM_swapImgRestore()" onMouseOver="MM_swapImage('ButtonThree','','_images/product_on.jpg',1)">
<img name="ButtonThree" border="0" src="_images/product.jpg" width="150" height="75" alt="products" /></a></td>
<td width="150"><a href="store.html" onMouseOut="MM_swapImgRestore()" onMouseOver="MM_swapImage('ButtonFour','','_images/shop_on.jpg',1)">
<img name="ButtonFour" border="0" src="_images/shop.jpg" width="150" height="75" alt="store" /></a></td>
<td width="150"><a href="profile.html" onMouseOut="MM_swapImgRestore()" onMouseOver="MM_swapImage('ButtonFive','','_images/profile_on.jpg',1)">
<img name="ButtonFive" border="0" src="_images/profile.jpg" width="150" height="75" alt="profile" /></a></td>
<td width="151"><a href="contactus.html" onMouseOut="MM_swapImgRestore()" onMouseOver="MM_swapImage('ButtonSix','','_images/contact_us_on.jpg',1)">
<img name="ButtonSix" border="0" src="_images/contact_us.jpg" width="150" height="75" alt="contact" /></a></td>
</tr>
</table>
<table width="1050" border="0" cellspacing="0" cellpadding="0">
<tr>
<td> </td>
<td> </td>
<td> </td>
</tr>
</table>
<p> </p>
<p> </p></td>
</tr>
</table>
</body>
</html>
the images and banner are showing up fine and i havent mistpyed any of the locations/file names. why doesn't the icon change colors (display the "on" image) when u hover the mouse over it? please help thanks in advance.
** i'm using Adobe Dreamweaver CS4He's right...
try instering this into the head tags of your html
<script language="JavaScript" type="text/JavaScript">
<!--
function MM_preloadImages() { //v3.0
var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
function MM_swapImgRestore() { //v3.0
var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
function MM_findObj(n, d) { //v4.01
var p,i,x; if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
if(!x && d.getElementById) x=d.getElementById(n); return x;
function MM_swapImage() { //v3.0
var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
//-->
</script>
Maybe you are looking for
-
Unable to Format External Hardrive
Hello all, This is kinda long winded. In short I can't format a new Maxtor external hard drive with Disk Utility because it hangs. It doesn't just hang when I select the Maxtor, but also when I select the internal. Is there a way that I can format it
-
Hi Guys, need to check if there is any solution on this... document posted in SAP takes the Application server time. Now if i have two or more plants at different location with a time difference , this effects a lot in deciding things. Can any one su
-
30 gb shuts off when shuffling...
Hello, I've had my 30gb for about a month now, and I've had just a few quirky issues with it. Mainly, when I set it to shuffle all songs, after a certain amount of time/songs, the thing shuts off, then turns back on. I'm not sure if this is something
-
Hi Experts, We are planning to implement SAP HANA Live for ERP operational reporting, I saw there are 786 views delivered with this which includes - 1) Query views 2) Reuse Views 3) Private Views Query views always contains the word "Query" at the en
-
Hi, I would like to ask a question
I'm trying to write a program that fills the applet window with a large ellipse, filled with any color, and that touches the window boundaries. However, I'm stuck on how I should I start; this is what I have so far written: import java.applet.Applet;