JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

What did you do with the String that the format method returns? I KNOW you are a better Java programmmer than this.

riahc3 commented: Java is completely crap. Thank you. +6
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

I'm worried. This thread has become very unheathy - just look at the number and kind of questions that are being asked. I know you have the Java skills to answer many of them yourself, and I don't think I'm providing the right kind of help any more.

So this may br my last post in the thread (maybe)...
Yes. Answered. What makes you think that that code will do anything other than print result (a double) in a system default format?
If you don't know how to use a NumberFormat then read the API doc, read the examples, Google if necessary. Don't just guess. The mistake in your code is a very elementary one.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Already answered (17 hours ago).

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

If you know its 2 dec places you can use standard Java NumberFormat to convert your result to string, then fix the decimal separator and add the currency.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

float/double are stored as 32/64 bits regardless. I guess you mean you want the result formatted to the same number of decimals as the source?

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Don't forget to use lots of print statements so you can debug your code, eg
at lines 32, 44 (etc) print the price String to see if it's been updated as you expected

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Seriously - time for a break. Trust me!

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

When you reach that level of frustration it's time for a break!

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Commenting standards do vary, and for a school assignment you do do what the teacher wants! I don't think your comments were "bad", and some were excellent. I would not deduct any points for that.

Just ask yourself - would a Java programmer understand that line or block of code? If so then it doesn't need a comment, if not then either improve the names you use, or add a comment.

Personally I think your code is pretty good. Well done.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Going through it one char at a time isn't such a bad thing. OK, maybe someone knows a really slick way, but often the most obvious solution is the one to use. You could collect all the digits before the decimal into one string, all the digits after the decimal into another, concatenate those together with a '.' inbetween, and that would be good input for parseDouble. (There's a method in Char to tell if a char is a digit).

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

There are loads of ways to do this using standard methods from the String class, or char arrays, or regular expressions (etc). I'm not going to deprive you of the pleasure of finding one for yourself ;)

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Re: comnments
Your commenting varies widely, some is excellent and some of it is redundant.
You should write your code with meaningful names so that someone who knows Java can read it easily. Comments like line 37 or 85 just clutter the code to no benefit.
On the other hand, you have some very good commenting, eg lines 312-315. Comments like that explain the overall content and strategy of what will follow, and any Java programmer will be able to read what follows and understand it perfectly.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

... ou dont need to write how a set of code conventions state ...

Possibly the worst advice of 2013 so far in this forum. Even if you never write a single program for real, even your teacher will read and mark your code. Coding standards and conventions are there to help everybody, and the sooner you engrain all the right habits the better.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Why do you think parseFloat will remove unwanted symbols? Did you check the API doc? The only thing it ignores is leading/trailing white space.
Because your currency symbol ould be anything you will have to remove it yourself.
Because your decimal separator could be anything you will have to parse the two parts of the number separately, or replace your separator with a standard . before passing it to parseFloat

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Looks OK so far - time to run some tests.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

You forgot to do the indexOf test for decimal separator to find which separator is actually present in the price (it should be just like the code for currency symbol). Then whe you have finished with that loop you will know both the currency symbol and the decimal separator, so then (and only then) you can then do the test to see whether the currency comes before or after the decimal.

Also line 13 you get the position of the currency symbol, so you don't need to do that again on line 20. Either way indexOf(position) has to be a mistake.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

No, its two independent loops, one after the other. 2D arrays lead to nested loops (one inside the other).
Please don't think in terms of me asking you to do things. I'm not running thei project, I'm just making some suggestions and hints. Take whatever you thnk is useful and add it to your own ideas.

Stop coding for a minute and think through the whole pseudo-code. Write your own complete pseudo code so you have the structure clear in your own head before getting into the details of the Java.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

You mught want to finish that bit first (exit the loop) then yes, you can do the decimal separator in exactly the same way.
(ps got other stuff on my plate right now, won't be able to respond so fast for while)

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

I was just using "source" as the name of the input string that you are trying to parse. And decimalSeparator for the . or , or whatever, exactly like the currency symbol.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Just break it down into smaller and smaller steps, eg stuff like...

parse:
   for each symbol in currency symbols
      if (source.indexOf(symbol) >= 0) this is the right symbol...
   ...
   if (source.indexOf(symbol)  < source.indexOf(decimalSeparator)) currency is prefix
   else  currency is postfix

format:
   result = (numeric value converted to simple syring)
   if (currency is prefix) result = symbol + " " + result
   else result = result + " " + symbol
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

OK, my eyesight isn't what it was, the , and . look the same on my screen!

How about some thing like this?

Parse the input to get a complete format defined by <decimal separator> <currency symbol> < currency prefix or postfix>... it's not difficult. ie:

  • have a list of known decimal separators. Search the input to see which it is, remember that
  • have a list of known currency symbols. Search the input to see which it is, remember that
  • check whether the currency symbol is before or after the number, remember that
  • (extract the digits before & after the decimal to get the numeric value).

You now have a complete format definition, so it will be easy to format any results using those 3 items.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

So
no thousands delimiters
decimal delimiter is always . (never ,)
curreency symbol is one of $€
$ is always prefixed, € is always postfixed
?
or are there more possibilities?

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

I'm not clear on your requirement. Is it like this...?

You have a String containing a formatted number. The formatting may include (arbitrary?) thousands delimiters, (arbitrary?) decimal delimiter, (arbitrary?) pre- or post-fix currency symbol.
You need to extract the numerical value to use in arithmetical calculations.
You then need to convert the result back toa formatted String using the same formatting as the original String.
Some/any of the formatting items (delimieters, symbols) can/cannot be pre-defined

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

where do I put the code for creating a new key binding?

Where you are initialising the window - eg in your GameCanvas constructor?
I don't really understand your ps. Are you saying the keyboard listener is being called or not?

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Please mark your thread "solved"; don't just leave it pending and apparently still needing help forever.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Sorry, I don't have time to study all your code now, but I'll bet 100:1 that it's a problem with keyboard focus. Youy add the key listener to your canvas, but that probably does not have the keyboard focus, so it doesn't get any keyboard events.
KeyListener is pretty much broken as a way of ordinary user input. Sun/Oracle know that, and supplied a better apporoach. Read this:
http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

You need to start a Timer with a delay of 10 secsonds. When that time is up the Timer will run a method that you provide, eg to send the next question. If the user answers in time, just cancel the Timer.
Here's a simple intro:
http://enos.itcollege.ee/~jpoial/docs/tutorial/essential/threads/timer.html

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

finds the rows and columns with the most 1s.

It's asking you to
Look at each row of the matrix, count the number of 1's in each row, find the row (or rows) with the most 1's (in this case row 2, with 3 1's compared to 2 1's in the other 3 rows)
then
Look at each column of the matrix, count the number of 1's in each column, find the column (or column) with the most 1's (in this case columns 2 and 3, both have 3 1's)

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

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 really mean "translate"? - in which case see stultuske's post
Or do you mean "transliterate" - replace each letter by it's nearest cyrillic equivalent regardless of meaning, in which case you could use something like this pseudo-code:

for each letter in the original string
   find that letter in the latinica array, remember its index
   get the  letter from the kirilica array at that same index
   append that letter to the output string

(There are other ways to approach this - eg use the input character's numeric value as an index into a single array of cyrillic equivalents, or create a Map with latin letters as keys and cyrillic letters as the values, but your approach is OK)

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

Just to understand what you are saying...
the option pane on line 9 displays, but then you do nor see any of the option panes on lines 18, 21 or 25?

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Static initialisers are OK, but in radhakrishna.p's example watch out for the scope of arr!
You can also use an instance initialiser http://docs.oracle.com/javase/tutorial/java/javaOO/initial.html which (to answer stultiske's question) save having to duplicate code between multiple constructors, and can be used in anonymous inner classes.

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

No, sorry radhakrishna.p, that explanation is not right.
The problem is that the parameter and the newCheckBox variable are local to the makeCheckBox method. As soon as that method finishes both those variables are discarded.
Some time later the ItemListener is called, which tries to use those variables, but they no longer exist.

If you declare them "final" then the compiler knows their value will never change. That means it can safely take a copy of those values for the ItemListener to use when it runs.

Every time you call makeCheckBox you get new versions of those two variables, and a new ItemListstener. Because these are new versions each time they can each have their own final values.

Just go ahead and declare them both final. If something is wrong at run time, it's something else, eg the "this" online 7 that refers to the ItemListener instance which will never be the source.

ps the if test on line 7 is redundant because every checkbox has its own unique listener instance.

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

If your question is answered then please mark your thread "solved" for our knowledge base.
Thanks
J

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

That looks right to me. I agree the CreditCheckFactory methods could be static - there's no need to instantiate a CreditCheckFactory.

(ps: Without some way to make isAgencyUp() false you can't fully test your code. And there's no obvious reason why isAgencyUp() should be public.)

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

Not sure what you're doing here, but to use intersects with an ArrayList you would have to loop thru the arraylist calling intersects for each of the (Rectangle) elements in the list

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.