JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

You don't say where you put it in the update method. The suggested code used it like this to stop the animation ofter the last frame was displayed if in "play once" mode...

 if (currentFrame > totalFrames - 1) {
   currentFrame = 0;
   if(playMode == PlayOnce){
      stopped = true;
   }
 }
game06 commented: ty +2
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

DId you try Liuqahs15's suggestion? It looked perfectly sensible to me...

ps: Liuqahs15: Nice post. And yes, Java has enums just like that.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

I think they're OK.
The original Sun Code Conventions" are the ones used by the developers of Java itself, and are the basis for most in-house Java standards as well.
http://www.oracle.com/technetwork/java/codeconv-138413.html

They start with these comments that I wish every developer learned by heart...

80% of the lifetime cost of a piece of software goes to maintenance.
Hardly any software is maintained for its whole life by the original author.
Code conventions improve the readability of the software, allowing engineers to understand new code more quickly and thoroughly.

ps For excellent examples of Java code look no further than the Java API itself - massively peer-reviewed, fully tested, huge scope, written by real Java experts for the widest possible audience. You can download a zip of the whole source code from Oracle's site.

For capitalisation of class names including acronyms you see both forms. Mostly using all capitals for the acronyms, but with some exceptions eg HTMLFrameHyperlinkEvent, JPEGHuffmanTable or XMLReaderFactory, but also XmlInlineBinaryData.

Here's a way to look at it:
Imagine your program had been written by someone else a year ot two ago, and they've moved on. Now your boss comes to you and says " they're changing the Summoner screens next week and I want you to update the Java code to match." As you start to look at the com.gmail.email.aviersproject package for the very first time, what kind of package & class names would you most hope to …

bguild commented: Excellent advice +6
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

The more descriptive it is, the easier it is for someone else to understand. In a real-worldenvironment this the most important consideration.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

(by following James's advice)

Not my advice. See my code for my best suggestion.

Pobunjenik commented: I meant your style of coding. :) +2
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster
  1. All you need is a boolean[][] - has the player targetted this cell? You can then use the existing Ship[][] array to see if that's a hit, or what to display to the user for that cell.

  2. Draw a grid - subclass JPanel and in the paintComponent method 2 loops to draw horizontal and vertical lines, OR nested loop to draw little boxes - easier that way to draw the box's contents at the same time.

ps Conway's Life is another really good thing to practice your Java with.

Pobunjenik commented: I already made a selfgenerating Game of Life, even has GUI. Wanna see? +0
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

You are mixing AWT components and Swing components - this is a formula for confusion and errors. Unless you have some very special reason you should always use Swing components rather than AWT. The swing components have names that begin with a J (JFrame, JButton etc). The ones without the initial J (Frame, Button etc) are the mostly-obsolete AWT versions.
Component btn_cancel = new JButton("Cancel");
Component class doesn't have action listeners. Why not simply
JButton btn_cancel = new JButton("Cancel");

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Now this is over, I'm still a bit unhappy with the code I posted earlier - in particular those almost-the-same loops inside the if (vertical) blocks. So here's a much cleaner/shorter version that has a width and height for each ship, so it doesn't need the vertical/horizontal boolean or the related if tests. It also opens up some possibilites such as an aircraft carrier that's 6x2 cells. There are a few other tidy-ups as well.

@pobunjenic: yhou may want to hang on to this one. I still can't see how you will know when a ship has been sunk using your current data structures.

import java.util.Random;

public class Battleships {

   private static Random random = new Random();

   public static void main(String[] args) {
      new Battleships();
   }

   final int ROWS, COLS;
   final Ship[][] shipGrid;

   Battleships() {
      // Milton Bradley version of the rules, (via Wikipedia):
      ROWS = 10; COLS = 10;
      shipGrid = new Ship[ROWS][COLS];
      addShip("AircraftCarrier", 5); 
      addShip("Battleship", 4); 
      addShip("Battleship", 4);
      for (int i = 0; i < 3; i++)
         addShip("Submarine", 3);
      for (int i = 0; i < 4; i++)
         addShip("Cruiser", 3); 
      for (int i = 0; i < 5; i++)
         addShip("Destroyer", 2);
      printShipGrid();
   }

   void addShip(String description, int length) {
      Ship s;
      int collisionCounter = 0;
      do {
         if (++collisionCounter > 100) {
            throw new RuntimeException("Too many random collisions, bguild was right.");
         }
         s = new Ship(description, length);
      } while (s.collidesWIthAnotherShip());
      s.addToGrid();
   }

   void printShipGrid() {
      for (int r = 0; r < ROWS; r++) {
         for (int …
Pobunjenik commented: I like your style. +2
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.

Java 7 API doc for StringTokenizer

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

I've altered your elegant solution to turn it into an almost identical solution that doesn't depend on luck or the implementation of java.util.Random.

That's OK, I just wish you had put that new code in its own method eg
List<Ship> getAllPossibleShips(...) { ...

:-)

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

"No skipping"?
My code adds all ships then displays them. Just try it!

Pobunjenik commented: Sorry, I must have missread your code. :) +0
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

This is all a premature optimisation.
I tried the full game setup (battleshup, 2 destroyers ... 5 subs) by the brute force random approach, and on average there are only about 10 unused random ships. Not a problem.
(code follows if you're interested - just a hack)

import java.util.Random;

public class Battleships {

static Random random = new Random();

   public static void main(String[] args) {
      new Battleships();
   }

   Ship[][]shipGrid = new Ship[10][10];
   int collisions = 0; // new random ships that were not used because they collided

   Battleships() {
      addRandomShip(5, 'B'); // battleship
      addRandomShip(4, 'D'); // destroyer
      addRandomShip(4, 'D'); // destroyer
      for (int i = 0; i <3; i++ ) addRandomShip(3, 'C'); // cruiser
      for (int i = 0; i <4; i++ ) addRandomShip(2, 'M'); // minesweeper
      for (int i = 0; i <5; i++ ) addRandomShip(1, 'S'); // submarine
      printShipGrid();
   }

   void addRandomShip(int length, char printChar) {
      Ship s;
      do {
         s = new Ship(length, printChar);
         collisions++;
      } while (! s.fitsOnGrid());
      s.addToGrid();
      collisions--;
   }

   void printShipGrid() {
      for (int r = 0; r <10; r++) {
         for (int c = 0; c < 10; c++) {
            System.out.print((shipGrid[r][c]==null)?'.':shipGrid[r][c].printChar);
         }
         System.out.println();
      }
      System.out.println(collisions + " collisions");
   }


   class Ship {
     final int row, col, length;
     final boolean vertical;
     final char printChar;

     Ship(int length, char printChar) {
        // create ship at random position
        this.length = length;
        this.printChar = printChar;
        vertical = random.nextBoolean();
        if (vertical) {
           row = random.nextInt(10-length +1);
           col = random.nextInt(10);
        } else {
           row = random.nextInt(10);
           col …
Pobunjenik commented: Very neat code, kudos! +1
bguild commented: Nicely done +6
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Comments:
I looked quickly at that code and decided I didn't have time to try to understand it. It's just too complex & nested. IMHO that's a result of not breaking the app up into enough classes.
Read the rules of the game - the most common noun is "ship". So I would start with a Ship class

class Ship
   final startRow, endRow, legth, direction, charForDisplay
   noOfHits = 0;
   sunk = false;

Then the game board is obviously an array of Ship instances (or nulls).

Now it's easy to write a Ship method to check if any of the ship's squares are already occupied by anthor ship and if not, to add the Ship to the board. Finally we have a simple method to generate ships at random locations/directions and try them until one fits.

It's also going to make things lot easier when you want to know if a Ship has been sunk etc.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

... or maybe this is clearer still:

boolean isLeapYear(year)
   if year divisible by 400 return true
   if year divisible by 100 return false
   if year divisible by 4 return true
   return false
ddanbe commented: Makes it cristalclear! +14
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Once again - it depends on the complete requirements, which we don't have.
But every time I see code like stultiske's first approach above, or code like

   public void playerOvalCollision()
    {
    }
    public void playerRectCollision()
    {
    }
    ...
    pubic void paint(...)
    {
    if(...)//randomly draw shapes
    r.drawOval(x,y,);
    else
    g.drawRect(x,y,width,height);
    }

it just screams at me "TWO CLASSES"!

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Scanners are just a simple fix for easy input, if you try to use them for formatted data you run out of steam really quickly. Here you have a scanner delimiting on blanks (default behaviour), but you want to keep month and day together.
You will find this easier if you just take full control yourself. Just read the file one complete line at a time (Scanner's nextLine() is OK for that), then use split(",") to separate the dates and costs. If you later need to separate the month and day you can split the date on " ".

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Short version: A JPanel is a container that you can add to a JFrame to help organise and lay out fields and buttons.
In your code
1. You have two JFrames and that's confusing you. CelsiusConverterCoded extends JFrame, so your new CelsiusConverterCoded() is a JFrame, but then you create another (unneccesary) JFrame on line 28.
2. You add your items to your JPanel OK, but you don't add the JPanel to your JFrame, so that's why you don't see it.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Do you inherit x, y, dx, dy from the Item class? If so you can just set dx in the default constructor for Bullet.

You haven't given enough info for a proper answer, but my instinct is that if you have two similar items then you should create two instances of a class.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Depends on the methods - do you mean different methods for one map (in which case see IIM's post), or that there are multiple maps each with its own implementation of the same method signature (in which case build a java.util.Map<String, Maps> to hold the name as key and a Maps instance as value then use the Map methods to get the instance by name.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Depending on how many things vary from level to level it may make sense to have a Level class with 4 instances, each instance having its own values for all counter etc etc.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Your methods are all static, and static methods cannot access instance variables without an instance. Your simplest fix is just to leave clientList where it is, but declare it as static so all the methods can access it. (There are all kinds of reasons why Java programs are usually not all static, but that's outside the scope of this particular issue - just be aware that it's generally a bad idea.)

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

"Whenever I try to run this nothing happens. "
Wrong.
It throws an exception which you cannot ignore.

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at Hobbits.main(Hobbits.java:8)

h is an array of size 3, so valid index values are 0,1,2
On line 8 you try to access index 3

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

This looks relevent: http://www.rgagnon.com/javadetails/java-0598.html (especially the first example)

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Snap!

stultuske commented: snap indeed :) was typing that while eating, took me a while ;) +14
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

If you want your "functional" buttons to do something you should add an action listener to them ;)

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

That's true, but let me just put in a word for Eclipse. IBM have a big investment in Eclipse, which supprts the SWT GUI classes that IBM tend to use in preference to Swing on Windows projects. IBM look like the biggest single employer of Java developers in the UK, so if that's also true where you are it's a good reason for learning Eclipse rather than NetBeans. (Personally I find both products functionally equivalent, I prefer to use NetBeans because it seems more polished, but most of my work has to be in Eclipse)

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

That's right for one thread. With two threads you could see

one
two
hello
hello

or

two
hello
one
hello

or

two
one
hello
hello

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Within a single thread statements will be executed in the correct order. Between two different threads there are no guaarantees unless you explicitly synchronise.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

OK, you have a number of methods, so that's something, but the requirement asks you to provide some classes as well as PetShopSimulation.
The obvious place to start would be those "needed classes".
These questions may help you think about it the right way...

"A pet shop contains multiple pets, namely two cats (Fred, Tom), two dogs ..."

What possible classes can you see here? How about Pet, what attributes does every Pet have? How do you think a Dog or Cat relates to Pet? How do you think Fred and Tom relate to Cat? What actions (methods) can a Pet perform?

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Neither. Stick to a programmer's editor and the commmand line compiler until you have a good feel for Java and what's going on. An IDE is just going to add confusion and learning curve to a situation that already has a lot of confusion and learning curve. Then move to an IDE. Professionals use NetBEans or Eclipse.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Here's a way to do it that will be right quite a ot of the time...

Get the Line2D that goes from the center of the ball to the center of the rect.
The Rect has 4 Line2Ds that form its top, botton. left side, right side.
There's a method in Line2D to tell if two Line2Ds intersect.
If the first line intersects the top line of the rect then the ball is probably touching the top
If the first line intersects the left line of the rect then the ball is probably touching the left side
etc
Not perfect - but probably good enough for now

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

"Urgent" means "I left this too late"?

DaniWeb Member Rules (which you agreed to when you signed up) include:
"Do provide evidence of having done some work yourself if posting questions from school or work assignments"
http://www.daniweb.com/community/rules

Post what you have done so far and someone will help you from there.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Scanner is "A simple text scanner", you can't use it to parse a binary file. Have a look at DataInputStream which reads binary data - although you may need to write a bit of code to handle text that's encoded as zero delimited bytes

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster
6:  Animal c = new Animal();    // creates a new Animal (1)
13: Animal e = new Animal();    // part of initialisation of Animal (1) - creates another new Animal (2)
13: Animal e = new Animal();    // part of initialisation of Animal (2) - creates another new Animal (3)
13: Animal e = new Animal();    // part of initialisation of Animal (3) - creates another new Animal (4)
...
13: Animal e = new Animal();    // part of initialisation of Animal (99999) - tries to create another new Animal but runs out of stack memory
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

We are just as confused as you are!
Questions:

  • Why does the right key move the camera left? ("... if user keep right key down. than camera should move left ...")
  • Why would moving the camera make the player fall down? ("... camera should move left.and my player should fall down ...")
  • If the tile size is 32 (line 9), where does the "5" come from in the Rectanges that you print?
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Here's a very simple demo of an animation with multiple things ("Sprites" moving about). YOu'll akready be familiar with many of the building blocks, so it shouldn't be too hard to read...

import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.TimerTask;
import javax.swing.*;

public class Animation1 extends JPanel {
   // Basic architecture demo for multi-sprite animation

   public static void main(String[] args) {
      // create and display the animation in a JFrame
      final JFrame frame = new JFrame("Animation 1 (close window to exit)");
      Animation1 animationPanel = new Animation1(600, 400);
      frame.add(animationPanel);
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setVisible(true);
   }

   private ArrayList<SimpleSprite> sprites = new ArrayList<SimpleSprite>();

   final static int TIMER_MSEC = 30; // mSec per clock tick

   Animation1(int width, int height) {
      setPreferredSize(new Dimension(width, height));
      sprites.add(new SimpleSprite(Color.blue, 0, 35, 2, 1));
      sprites.add(new SimpleSprite(Color.red, 0, 250, 2, -1));
      startTimer();
   }

   void startTimer() {
      // use java.util Timer rather than javax.swing Timer
      // to avoid running intensive simulation code on the swing thread
      java.util.Timer timer = new java.util.Timer();
      TimerTask timerTask = new TimerTask() {
         @Override
         public void run() {
            updateSimulation();
         }
      };
      timer.scheduleAtFixedRate(timerTask, 0, TIMER_MSEC);
   }

   public void updateSimulation() {
      // called by Timer every TIMER_MSEC milliseconds
      for (SimpleSprite s : sprites) {
         s.update(); // update position of the sprite
      }
      repaint(); // request Swing to schedule re-paint of screen
   }

   @Override
   public void paintComponent(Graphics g) {
      // screen refresh - called by Swing as needed
      Graphics2D g2d = (Graphics2D) g;
      paintBackground(g2d);
      for (SimpleSprite s : sprites) {
         s.draw(g2d);// draw the sprite at latest positions
      }
   }

   void …
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

No, I did read carefully, because I was so surpised by what you wrote. If you had defined and used some artificial class example then the point would have been clear. But by chosing JFrame you chose a well-known class that has well-known methods, and what you wrote was incorrect for that class.
I commented because a novice could read what you wrote and believe that you can't change the title of a JFrame if you have set it in the constructor. It was just an unfortunate choice of example, that's all.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

In the first case, if you want to change the title of the jframe sometime later in your code ,you CANT change it . You have to create a new object inorder to change the title which is not what you need.

@harinath: Do you have any reference material or sample code to support this assertion?

You may want to run this:

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;

public class TitleChanger {

   static JFrame frame = new JFrame("Harinath says this can't be changed");
   static int counter = 0;

   public static void main(String[] args) {
      frame.setMinimumSize(new Dimension(500, 200));
      frame.setLocationRelativeTo(null);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setVisible(true);

      new javax.swing.Timer(3000, new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            frame.setTitle("changed " + ++counter);
         }
      }).start();

   }

}
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Don't worry, this one often catches beginners out!
You declare the method as returning a boolean, so the compiler checks your code to ensure that, no matter what happens in the if tests, you always return a boolean.
In your code, if all three if tests are false, you will get to line 94 without returning a value. You will need to add one more return statement to guarantee that you always return something.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

You've run into a very common problem with Scanner. After nextInt() the following new line character is left unread, so when you do the next nextLine() you get a zero-length string ie ""
It's a messy bit of design in Scanner, not your fault really.
When yu have a nextInt() follwed by a nextLine(), you need to add an extra dummy nextLine() just to get rid of the new line character

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Here's the usual way to do it:
in the bullet class have an update method (where you do x+=dx; etc)and a paint method.
Maintain a list of all the current active bullets, and make that list available to the main class.
In the main timer method call each bullets update method.
in the main paint method, call each bullets' paint method.

The simplest way to share the list of active bullets is to have a public static ArrayList<Bullet> in the Bullet class so any other class can access that list to iterate through the bullets.

If you are going to have different types of things moving around then you should consider having them all implement the same interface or inherit from the same abstract superclass (ie the update and print methods), then all you need is a single list for everything that moves.. j

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

I agree with ~s.o.s~ The coding conventions he linked to are not mandatory, but they are the ones used most widely, particularly in all the Java API code. All working Java developers will be familiar with them, so if you want your code to be quickly and easily readable for a majority of programmers you should stick to them. If you start work as a Java coder your employer will have mandatory local coding standards that you will have to follow, and they will almost certainly have the same base.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

For smooth movement, this is how people normally do it...
in your game loop (timer actionPerformed) you execute the camera_pos_x += camera_speed; and call repaint() every time. cameraSpeed is initially zero.
When the user presses the Right key, you set camerSpeed to +5. When the user releases the key you set cameraSpeed back to zero. That way the camera will move smoothly right for as long as the key is down.
You don't say how often your timer fires, something like 25/sec (40 mSecs delay) would be a good starting value.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

case 4: System.exit(pin);

System.exit() immediately terminates your whole program, so it's a bad idea to call it when you just want to exit the current loop. You haven't indented your code, so I'm not going to waste time trying to understand how your loops are nested, but I would start by removing the System.exit.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

The panel that needs to be repainted is display_class, so when you change any values in the simulation you need to call display_class.repaint(); to see the result.

ps I find your variable names quite bizarre - I hope they're not the result os some misunderstanding? Eg you have an instance of Display which you name display_class. It's not a class, it's an instance. It would make more sense if it was named displayInstance or theDisplay or somesuch. There's also a Java convention that variable names use "camel case" (like my examples) rather then underscores (except for constants that are all upper case)

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

There's no one "correct" answer. In simpler cases the controller initialises a model, then initialises the GUI and passes it a reference to the model. The GIU can then interact directly with the model. In more complex systems the controller plays a bigger role in mediating the GUI/model interactions and hiding each side's complexity from he other side. My guess is that for a college project the first approach will probably be easier.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster
  1. Make them buttons (or JLabels) in a JPanel and move them as required (use a null layout manager, set the button attributes to hide the usual borders etc)
  2. Just draw them on a JPanel and have code that checks the mouse click coordinates against the position/size/boundaries of each element to see which one (if any) the click was in

Without more info on your game its hard to say which would be a better choice for you.

Sacrificer_911 commented: Thanks :) I'll give that a try +0
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

If you want integer values from Random you should use nextInt rather than rounding a random float - see the API doc for Random to appreciate the extra stuff needed to get good random ints.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

[Ljava.lang.Double;@35960f05 is what you get when you call toString() on an array of Doubles (which is what println does when you print anything - it calls toString() to get a printable version). That toString method is inherited from Object.

There's a method in the Arrays class that converts arrays to the kind of string you want -
System.out.println(Arrays.toString(myArrayThatIWantToPrint));

jspence29 commented: That worked Thanks! +2