JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

You just copy/pasted your assignment without even a moment taken to explain what help you need. That's highly disrepestectful to the many people who give their time to help others here.

There are lots of people here who will freely give their time to help you become the best Java programmer you can be. There's nobody here who is interested in helping you cheat or doing your homework for you.

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

Looks to me like that value is a valid integer, but its not a valid int because it's too big, >= 2^32. You could use a long instead of an int.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

It really is that simple, eg let's suppose the2D array is called weights, then if the user asks if row B, position 4 is occupied, your test is

if (weights[1][3] > 0)

(remember Java arrays start at element 0, not element 1)

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

You can use System.setOut(PrintStream out) to redirect all System.out.print data to the stream of your choice. If you use a ByteArrayOutputStream then you will get all the output in a byte array that can easily be converted to a String.
Is that what you meant?

JeffGrigg commented: Yep; that's the way I usually do it. +6
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Yes. Whenever you see code repeated like that, with one value changing from line to line, you just know it should be a loop. Eg::

for(int i=0;i<str1.length;i++) {
   graphics.drawString(str1[i].toUpperCase(), 360, 50 + i*10);
}
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

There are lots of people here who will freely give their time to help you become the best Java programmer you can be. There's nobody here who is interested in helping you cheat or doing your homework for you.

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

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

In general a jar will run on any higher jre version. It's possible you may run foul of tighter security settings, as there have been a number of changes there since 1.5.
How exectly does it "fail"? - absolutely nothing happens - runs but wrong results etc?
Did you try running the jar with java.exe (as opposed to the normal javaw.exe) so you can see the console output?

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

You are drawing them all at the same position 250,200
You need to increment that position's x or y value after each print so the next string goes to a different position

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Personally, the thing that surprised me here was that job.print(); doesn't throw a PrinterException if there is no Printable specified. That would have made it immediately obvious where to look. Oh well, maybe for Java 9?

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

OK, here's what you did wrong...

In your class you created a printer job...

PrinterJob job = PrinterJob.getPrinterJob();

Then in the actionPerformed you created another one ...

PrinterJob pj = PrinterJob.getPrinterJob();

Then you proceed to mix the two up ...

job.setPrintable(this);
if (pj.printDialog() == true)
...  pj.print();

That's why your print doesn't work. I'm sure you can see how trivial the fix is, knowing that.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

You overide paint for the whole applet, but in it you only paint the image. That leaves the rest of the applet unpainted. You could try a super.paint(g); as the first line of your paint, so the rest of the applet gets drawn properly befroe you draw the image.
A better solution is to have your own trivial subclass of JPanel for the image, then you only need to subclass paint for that component, not the whole applet.
An even better solution is to convert your image to an ImageIcon and put that in a JLabel. Then there's no need for any custom paint code at all.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

I'm comparing your code with a small demo I wrote a while ago - I thought the demo was pretty minimal, but your code is a lot smaller, so maybe you're missing something essential. Just in case you may find it useful, here's that demo...

The interface is just one method that takes an int, adds one to it, and returns the result...

package misc;

import java.rmi.Remote;
import java.rmi.RemoteException;

public interface RMIInterface extends Remote {

   public int plusOne(int i) throws RemoteException;
}

The client just locates the server, calls the remote method and prints the result...

package misc;

import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

public class RMIClient {

   public static void main(String args[]) {

      try {
         RMIServer.rmiStarter(RMIInterface.class);
         Registry registry = LocateRegistry.getRegistry();
         String serviceName = "PlusOne";
         RMIInterface server = (RMIInterface) registry.lookup(serviceName);
         int i = server.plusOne(2);
         System.out.println("RMIClient result: " + i);
      } catch (Exception e) {
         e.printStackTrace();
      }
   }

}

The server is more interesting because it includes some bullt-proofing code to avoid some common configuration problems... (1) start the naming server if one isn't already running and available, (2) set the java.rmi.server.codebase System property, and (3) creates a security policy file that allows everything and uses that.

package misc;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;

public class RMIServer implements RMIInterface {

   @Override
   public int plusOne(int i) throws RemoteException {
      return ++i;
   }

   public static void main(String[] args) {

      try {
         rmiStarter(RMIInterface.class);
         Registry registry = startRegistry();
         String …
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Recent Java versions have direct support for embedded scripting languages, including sharing data etc. Here's a tiny eg I had lying about.

// evaluate arbitrary jscript boolean expression...
ScriptEngine js = new ScriptEngineManager().getEngineByName("JavaScript");
try {
   String condition = "a==b"; // expression to evaluate
   js.put("a", 2); // value for a
   js.put("b", 3); // value for b
   Object result = js.eval("var a,b;" + condition + ";");
   System.out.println(result);
} catch (ScriptException ex) {
   ex.printStackTrace();
}

http://docs.oracle.com/javase/6/docs/technotes/guides/scripting/programmer_guide/

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

I think your original if test was correct. The problem is the semicolon at the end of line 8, which terminates the while block right there, so the message dialog is not part of the while, and always gets executed. Just get rid of that ;

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Nopbody in their right mind will waste a single moment trying to debug code that sytematically and universally discards all its Exception info. They could waste hours when the answer was always there in an ignored Exception's messaage and stack trace.

Remove all the "throws Exception" clauses from your method definitions, catch all your Exceptions, and put an e.printStackTrace(); into all the catch blocks. Then run it again, then let's try to debug it.

Begginnerdev commented: Yep! +9
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

You just copy/pasted your assignment without even a moment taken to explain what help you need. That's highly disrepestectful to the many people who give their time to help others here.

There are lots of people here who will freely give their time to help you become the best Java programmer you can be. There's nobody here who is interested in helping you cheat or doing your homework for you.

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

It's just like the Quit button you already have, but in the ActionListener instead of the run() method just being system.exit(); itshould have the necessary code to set the text of the field you want to update.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Those fully-qualified swing class names look like GUI builder generated code - so no problem IMHO.
But I agree the variables names should conform to the normal Java standards. (And perfect indentation would help readability.)

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Like I said before, use Day for the outer index, and hard-code the inner indexes, eg

   System.out.printf(leftAlignFormat,"Day "+ Day, myArray[Day][0], myArray{Day][1] etc

ps: Java convention is that variables have names that start with lower-case letters (class names start with a capital)

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster
  1. Yes, that declaration is OK
  2. Looping goes like:

       for (int i = 0; i < myArray.length; i++) {
          for (int j = 0; j < myArray[i].length; j++) {
              do stiff with   myArray[i][j]
          }
       }
    
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Declare a 30x5 array (an array of 30 elements, each of which is a 5 element array of ints).
use your Day variable (line 14) to index the outer array, and hard-code the inner array refs, eg myDataArray[Day][0] instaed of the first "i" on line 16

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

There's no reason to use an integer field to store phone numbers. You won'r be doing arithmetic with them.
Most people prefer to enter and see them with some formatting, eg a - or blanks between groups of digits. There is also the convention for international prefixes that looks like "+33 (0)5 53 etc". Those are all very good reasons to hold the original String, and not try to parse it as integer.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

I do not know how to make it so that, when you guess a correct letter, it reveals that letter in the hidden word while still keeping the other parts of the word hidden.

You can use a StringBuilder - it's like a String but you can update individual characters in it. So start with a StringBuilder that just contains the right nunmber of '.' characters. As the user guesses correctly you can replace the corresponding '.' with the correct character. You can print a StringBuilder just like printing a String, so no problems there! À Bientôt J

http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Yes, absolutely, a very good thing to do. The advantage of also running format is that you spot errors immediately, without having to run and interpret test cases. It's a fundamental part of the philosophy of Java that you should try to prevent errors at compile time rather than wait until you run things - hence strict typing, uninitialised variable checks etc.
Way way back in my IBM days we had a rule of thumb that given 7 stages of OS development
spec / design / code / unit test / system test / user test / deployment
the cost of finding and fixing an error increases by a factor of 10x at each stage. Now maybe that should be 4x ? but either way the moral is to fix things at the earliest possible stage.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Key listeners have their place as a low-level interface to keyboard input, but for responding to individual keys key bindings are more appropriate and tend to result in more easily maintained code. Key listeners are also difficult if the key binding is to be active when the component doesn't have focus.

(That's from the Oracle Java Tutorials - http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html )

Check out that tutorial. Key Listeners may look like an easy approach but they are full of pitfalls and problems, and are really only appropriate when you need to "get down and dirty". Key Bindings may look a bit more complicated at first, but work much better. They are based on Actions, so if you update your button handing to Actions as well you will have one set of code that deals with mouse clicks and keyboard interchangeably

Ms commented: : ) okay thanks +0
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

I tried implementing the switch, ... I was using str in the switch,

The first word of each line is in the first element of the array where you split the line, so that's the string you can switch on
switch (array[0]) { ...

BufferedReader is the best way to read whole lines.

Hanyouslayer commented: Oh....haha +0
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Line 44 it's unlikely that getText will return null. For an empty field it will return an empty String, ie "". You can test for equals(""), or use length()==0

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Onl line 4 you create an ArrayList, and a reference variable that refers to it.
On line 11 you call addB passing the reference (the variable called list) to your ArrayList.
In that method you get a copy of that reference and you call that list1.

Now list and list1 contain the same value, ie a reference to your ArrayList. It doesn't matter whether you use list or list1, they both refer too exactly the same ArrayList

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Scanner was intended as an easy tool for beginners, but in reality it's a poor implementation, and causes more problems than it solves. Forget it.

I would just read each line of the file, then split it onto an array of words using String's split() method.
You can then use a switch on the first word (Java 7 and later) and handle the remaining words as appropriate in the different cases.

(ps " I don't need any help with the actual drawing of the shapes" - suggest you check back into that thread. A couple of posts explain why your implementation is badly broken)

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

mKorbel, as usual, is right. You may think that code is OK, but it's going to fail.

Calling getGraphics and just drawing there hasn't worked since Java 1.5 made double-buffering the default. It may work (especially the very first time), but will fail totally later, eg when the window is resized. The only safe approach is to override paintComponent for your panel.
http://docs.oracle.com/javase/tutorial/uiswing/painting/index.html

Thread.sleep sooner or later causes problems in a Swing environment, typically because it gets executed on the Swing event dispatch thread and blocks the whole GUI. Use a javax.swing.Timer for GUI animation
http://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Dining Philosophers is a lot of fun, and trickier than it looks. It's a classic where the solution is hard to wrap your brain around, but really not so hard once you've got it.
Strongly recommended for building your threading qi

somjit{} commented: thanks a lot ! +5
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Java language is somewhere between c++ (hard) and Basic (easier), but that's not what matters. It's the API or libraries that you need. IMHO the Java API is easier than .net, and both are vastly easier than having to write all that stuff yourself.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

For a deep copy you need to copy everything, all the way down, so instead of

board[i][j] = other.board[i][j];

it should be

board[i][j] = a copy of (other.board[i][j]);

(how that works depends on how you can copy whatever is on other.board[i][j])

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Hi, sorry my last post was short and not followed up - I was offline for three days. :( Here's a better answer:

Instance methods are always bound at run time, according to the actual class of the object that is used in their invocation. The object is first searched for an implementation of the method, and if none is found the superclass is searched (etc).
The type of the reference variable is just used by the compiler to ensure that the call will be valid at run time. That may be an interface, or an abstract class, but as long as it defines the method signature we know that any object the variable refers to at run time will be a concrete class with a (possibly inherited) implementation of the method.

Static methods are bound differently, and if you use a variable to invoke them then the type of the variable is used to bind the corresponding static method at compile time. Because this can be very confusing (and inconsistent with instance methods) the compiler now discorages that type of call, and encourages you to call static methods using the class name.

somjit{} commented: don't remember reading this anywhere.. really helpful answer. +4
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Instance methods are called based on the actual class of the object used to call them. The type of the reference variable is irrelevant.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Looks like a bug to me... shouldn't it be stack.size() - the number of items to pop off stack and push onto this?

Although for clarity and safety I would prefer to see something like

while (stack.size() > 0) {
   push(stack.pop());
} 
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

... unless the String includes any supplementary characters (which are represented by surrogate pairs of chars). The characters in a String do not necessarily correspond one-to-one with chars. There's more to text on Earth than just ASCII you know.

(OK, maybe I'm just being pedantic, but as a French speaker I get over-sensitive about people who think there are only 26 characters in the alphabet, all represented by char values < 127)

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

a 2-D character matrix is at the end of the day a string array right ?

Wrong! A String is not a char[], and a String[] is not a char[][]. That's a mistake that people quite often make if they come to Java from a C-based language.

somjit{} commented: "Wrong!" just woke me up ;D thanks +4
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

newLS.rev() returns Pain instead of a reversed stack

On the basis of what you have posted... no, it doesn't!
The definition of the rev method above shows a return type of LinkedStack<T>, so there is zero possibility that it returns a value of "Pain". There is obviously something else going on here that you have misunderstood. We need more details to help any further

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

You can replace your drawPolyLines with a drawPolygon if you want the path to be closed.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

So step 1, 2, 3(for worst case) and 7 will occur once

No, that's completely wrong - see below

System.currentTimeMillis() returns the current time in milliseconds.
But time complexity is more theoretical than that. Just timing algorithms won't tell you that unless you run many very very large test cases.

You have to examine the code and how it scales up with large data values to determine the time complexity.
Eg, with your example the outer loop will be executed n times. The inner loop will be executed on average n/2 times for each time the outer loop executes. So the code in the inner loop will be executed n*n/2 times - that's O(n^2).

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Yes. Show some initiative and get on and do some work.

Do some research to fill in any gaps in your knowledge (use the internet). Write and test both implementations. Compare their speeds...

If your tutor gave you this assignment then obviously (s)he expects it to stretch you, but (s)he also expects that you should be able to do it.

If you get stuck you can come back here, explain what you have done so far, and clarify exactly what help you need.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Don't reload the image file every time. Do it just once at startup and keep a copy.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

I assume your tour[] array just contains the city numbers in the right order, yes?

so the first line to draw is from (the x,y coords of the city identified in tour[0]) to (the x,y coords of the city identified in tour[1]). The second line is from (... tour[1]) to (... tour[2]) etc ... I'm sure you can see the pattern there and how to code that loop?

ps please don't call me "sir"
!

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

That's a good start! At least we don't have to striggle with basic Swing concepts!
It looked to me like the weight array holds the distance/cost bewteen each pair of cities, yes? (It's size is n^2). I was looking for some data that holds an x and a y coordinate for each city (size 2*n). You need that to know where to draw each city because your paint routine needs to look something like this (pseudocode):

for each city
   draw a small box (or circle etc) at the x,y coordinates of the city
for each step in the tour
   draw a line from (x,y coords of the city at the start of this step) to (x,y coords of the city at the destination of this step)
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Java is case-sensitive. string and String are not the same. String is a class name and is spelled with a capital S

Madiya122 commented: Thanks for pointing out. Really appreciate it. +0
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

They're simple literals. Just like the "h", "o", "u" etc at the start of the string. Anythingthat's not part of a "format specifier" is"fixed text" (ie a literal).
See the API doc for the Formatter class for complete detailed descriptions of all the format string options.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

That's right.
Similarly, rand.nextInt(25) will give you random ints in the range 0-24 inclusive.
Think of the parameter as defining how many different values it will return.

JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

If OP really doesn't have sufficient ability or initiative to find information on prime number programs on the web then simply giving them something to copy & paste into their homework is helping nobody. Not their teacher, not a potential employer, not their hard working colleagues, and least of all not the OP.

ps: Anyone thinking of using subhraakasuny's code should also be aware that it's a poor example of Java code. An int called "flag" that just has values 0 and 1 clearly identifies someone who (a) doesn't care about variable naming and (b) hasn't heard of booleans. It's also inefficient (tries modulo by every number when it only needs primes or at the very least just odd numbers after two; keeps going even after proving num is not prime).

subhraakasuny commented: Being a beginner,It is really helpful to me to understand the fault. +0
JamesCherrill 4,733 Most Valuable Poster Team Colleague Featured Poster

Your random numbers are in the range 0-12 so your first loop will never be able to process 14 letters, but it keeps on trying...

Ps. Your second loop will never select Z, for the same reason. It seems you have mistaken the contract for nextInt - review the API doc ;)