javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

For 2D arrays

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Fist of all print the query and run it directly at the database and see if it runs.

Then, create a new class with one main method. Inside do this:

public static void main(String [] args) {
  Connection conn = null;
  Statement st= null;
  ResultSet rs = null; 

  String query = "select * from PatientTable where patientNo = '123'";
  // select * from PatientTable where patientNo = '123'

  try {
       Class.forName("your driver");
       conn = DriverManager.getConnection(url, userid, password);
       st = conn.createStatement();
       rs =st.executeQuery(query);
  
       if (rs.next()) {
           System.out.println("Found");
       } else {
           System.out.println("Not Found");
       }
  } catch (Exception e) {
     System.out.println("Exception e: "+e.getMessage());
     System.out.println("----------------------------");
     e.printStackTrace();
  } finally {
     try { if (rs!=null) rs.close(); } catch (Exception e) {e.printStackTrace();}
     try { if (st!=null) st.close(); } catch (Exception e) {e.printStackTrace();}
     try { if (conn!=null) conn.close(); } catch (Exception e) {e.printStackTrace();}
  }
}

Try to keep the finally the way it is; close them in that order. (Actually I don't know if the order that you close them makes a difference but just in case follow that order.)

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

In a few hours I will give you a more detailed suggestion. For the time being, can you run the code again, and post the entire exception stack trace.:

catch(SQLException exc){
  exc.printStackTrace();
  throw exc;
}

Also there would be some line numbers. Go to those files the lines refer and post those lines as well. Of course you will post only the lines of your classes, because the stack trace will print and other class lines as well.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

For overloading constructor:

private String Jazz;

    public JazzBandsInstruments(String p_Instruments, int p_Members, String p_jazz) {
        super(Instruments, p_Members);
        setJazz(p_jazz)
    }

Apart from that does the code compiles?

Make a list of all the requirements and check your code where they are implemented. If there is something you are not doing then post specific questions.

Then in your main just call the constructors and the methods. I would suggest, since you have more than one constructor per class, to make 2 instances of each object:

JazzBandsInstruments j1 = new JazzBandsInstruments();
j1.set...();
j1.set...();
j1.set...();
// print

JazzBandsInstruments j2 = new JazzBandsInstruments("arg1", arg2, "arg3");
// print
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

The thread is still on the server and is open, so anyone can respond. The answer will be helpful to those of the network the solution of that problem. Your comment is not smart.

Respond yes, But give away the answer no. This is not a forum where the memebers do other people's work

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

I took a closer look to your code and here is what I suggest.

First you need to read all the values of the array and then check for equality. You do this:

for ( int l = 0; l < n; l++ ) {
        numbrid[l] = sisend.readLine();
	for ( int j = 1; j < numbrid.length - 1; j++ ) {

You read the 1st number but then you loop the entire array. But the rest of the elements of the array are null.

I suggest to do something like this:

for ( int l = 0; l < n; l++ ) {
        numbrid[l] = sisend.readLine();
}

for ( int i = 0; i < n; i++ ) {
   for ( int j = [B](i+1)[/B]; j < n; j++ ) {
       // compare the values
}
}

Also check the index of the second (inner loop) I think that it is more appropriate. Remember that with each loop the first index increases by one. So if you want the second loop to look after that index don't set it to 1 but to i+1.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Why don't you use: startsWith, instead of equals. Of course that means that for these the methods will return true:

1234
12345
"12345".startsWith("1234") = TRUE

1
123456
"123456".startsWith("1") = TRUE

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

You get this exception:

java.net.MalformedURLException: unknown protocol: c

When you read the file. I assumed that your file could not be read dut to a tag error.

But then I see in your file this:

<INPUTFOLDER>C:\</INPUTFOLDER>

I am no expert in xml, But can you try this:
Call the command that gives you the exception in a separate main method and see if you get the same exception.:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                DocumentBuilder docBuilder = factory.newDocumentBuilder();
                Document doc = factory.newDocumentBuilder().parse(fileName);

If yes, change the value of C:\ with something else and see if you will get the same error

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Can you post the contents of the xml file?

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Because bold doesn't show very good try to add some color as well next time.

Is this the line:
Document doc = factory.newDocumentBuilder().parse(fileName)

If yes the problem might be with the contents of the file.

Also I noticed this:

public boolean writeToOldFile(String str_fileName) {
        str_jobName = txt_jobName.getText();
        String str_settings = "<JOB>\n" +
                "<JOBNAME>" + str_jobName + "</JOBNAME>\n" +
                "<INPUTFOLDER>" + str_inputFolder + "</INPUTFOLDER>\n" +
                "<FILEMASK>" + str_fileMask + "</FILEMASK>\n" +
                "<PROCESSORDER>" + str_processOrder + "</PROCESSORDER>\n" +
                "<RETAINFOLDER>" + str_retainFolder + "</RETAINFOLDER>\n" +
                "<OVERRIDEFOLDER>" + str_overrideFolder + "</OVERRIDEFOLDER>\n" +
                "<ERRORFOLDER>" + str_errorFolder + "</ERRORFOLDER>\n" +
                "<POLLINTERVAL>" + str_pollInterval + "</POLLINTERVAL>\n" +
                "<JOBBATCHFILEPATH>" + str_jobBatchFilepath + "</JOBBATCHFILEPATH>\n" +
                "<JOBBATCHPARAMS>" + str_jobBatchParams + "</JOBBATCHPARAMS>\n" +
                "<JOBLOGPATH>" + str_jobLogPath + "</JOBLOGPATH>\n" +
                "<JOBEMAILTO>" + str_jobEmail + "</JOBEMAILTO>\n" +
                "<JOBALTEMAILTO>" + str_jobAltEmail + "</JOBALTEMAILTO>\n" +
                "</JOB>\n" +
                "[B]</APOLLERSETTINGS>[/B]\n";

Is it correct that you close the APOLLERSETTINGS without being open? Do you open it somewhere else?

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

In my previous post I suggested for you to print the query and try to run it at the database in order to see if it will run. Try that, and tell me if it brought correct results.

Also search your code again in case you have something open. Remember:

// open connection, Statement, ...
//run query
// close everything in the finally

I searched the web for that error. You should have done the same.

Can you try and using this command in order to create the statement:
>> st =conn.createStatement()

Also from what I have found, can you check your code if you are using any commands like setAutoCommit() ?

If the above suggestion don't solve your problem can you post the query you used to create the table. Also the data types of the columns would be helpful.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

You wrote this:

String ptNo=null;
Patient pt = getPatient(ptNo);

You passed as argument null. It is in front of your eyes!

With every error you got you didn't made a single attempt ot try and fix it. You just posted and expected others to tell you the asnwer so you can continue until you make the next error.

You got an SQLException. Did you try to print the query and run it in order to see what is executed. The above has nothing to do with java. It is common sense.

There is a difference between being a beginner in java and not being able to think for yourself. I have told you everything you need to know to fix this. If you can't put some simple code together then I am not going to write the code for you in order to get your intership.

Fix this and if you have another question that has nothing to do with this, then start a new thread and someone will answer it. I have wasted my time here.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

So for my purposes of understanding this, my error in my ways was that i was closing the stream before i had finished writing, so technically it was outputting the results correctly but only processing one line to file?

Thank you by the way javaAddict and yep i checked out your bike too in the process. You have to make sure she stays royal that one; will get a fair bit attention.

I assume that your problem has been fixed. Do you get the results that you want?

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

From what I see you just copied my code blindly. You didn't even bother to understand anything. How do I know this?
For starters, the method takes as argument the patienNo, but instead of using that, you used this: "PatientNumberList.getSelectedValue()"

And when you call the method you call it with null:

String ptNo=null;
Patient pt = getPatient(ptNo);

So you need to decide, do you want an argument, or you will take the value directly with the getSelectedValue() ?


Once you get the Patient you can do whatever you want with its values. Set them to text fields, open a new JFrame and display them, ...

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Inside the for you do this:

BufferedWriter bw = new BufferedWriter(new FileWriter("audits.txt"));

String s = lines[i];
bw.write(s);
bw.flush();
bw.close();
}

Meaning that with each loop open the file, overwrite that was written and you close.

You need to open the file, write whatever you want and when you are done close it:

BufferedWriter bw = new BufferedWriter(new FileWriter("audits.txt"));

for (int i=0;i<lines.length;i++) {
  String s = lines[i];
  bw.write(s);
  bw.newLine();
}

bw.flush();
bw.close();
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster
public Patient getPatient(int patientNo) throws SQLException {
// Connection, statement, ResultSet

// Call query

// get the info

Patient pt = new Patient();
pt.set...(..)

// close Connection, statement, ResultSet

return pt;
}

If there is no patient found, you can return null, and after you call the method you check that and print the right message:

Patient pt = null;

..

if (rs.next()) {
 pt = new Patient();  

 pt.set...(..)
}

return pt;
Patient pt = getPatienNifo(ptNo);
if (pt==null) {
  // show message 
} else {
  use the pt values to set them wherever you want
}

If you want it to be added to a JTable check the setModel method of the JTable class. You will use a DefaultTableModel instance. Check the API and you will find methods that can help you.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Of course it doesn't print anything because you have things inside the if. And the if statement return false.
Every time you run that code the numberOfAttempts is initialized to zero. So it will never reach 3. This is not where you need to declare it.
You should add a "System.out.println" before the if to see what is the variable's value. Try to do that every time you are stuck.
Its value shouldn't be initialized to zero every time you run the code, that is why I didn't declare anywhere near that code.
It should be declared somewhere where its value isn't set to zero every time you try to log in. Perhaps as a global variable.


If you can't understand that, then you need to study more and don't do so complex things. There is nothing more I can explain on this matter. Everything you need so you can fix it, have been told.

You asked me why you don't see the message, when the if statement is right there in front of you, you wrote it. Don't you know what if statement do? Did I have to tell you that the code inside the if doesn't execute because the if is false?

If you have any more questions on something else then I will answer them. But these things are not for beginners as you mentioned.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

I cannot help if you don't follow my suggestions. This is what I wrote:

if (rs.next()) {
} else {
 [B]numberOfAttempts++;
 if (numberOfAttempts>3) {
   // Attempted to log unsuccessfully for 3 times
 }[/B]
}

And you wrote:

if(rs.next()){
                }
                else{
                    [B]int numberOfAttempts=0;
                    while(numberOfAttempts<=3) {
                    JOptionPane.showMessageDialog(null, "Login failed, try Again");[/B]
                    }
                    [B]numberOfAttempts++ ;
                     if (numberOfAttempts>3) {
                     System.exit(1);
                     }  [/B]             
              }

The while loop will always be true:

int numberOfAttempts=0;
while(numberOfAttempts<=3)

So it will never end. The idea is whenever you don't enter correct username, password to increase a counter. If the counter becomes greater than 3, (3 unsuccessful attempts) exit the application.
And you went and declared it in the else { .. }. Meaning that it will always be 0 and will never reach 3.
Can't you imagine where it should have been declared or you didn't think that upon successful log in to initialize it back to 0?

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

I have never tried that before but you can do this and see if it works:

Instead of sending the value of the combo box have 2 hidden fields:

<input type="hidden" name="hiddenList1" value="" />

When you click the button to submit run a javascript that loops the list and appends its values to the hidden field. Then when you get the request, you can use the split() method to separate the values.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Use the method of JTable: setModel(TableModel dataModel).
Create a DefaultTableModel object and pass that as parameter to the setModel method.

Whenever you want to insert a new row, just call the method addRow of your DefaultTableModel instance. You don't need to call the setModel again as long you are calling the addRow method of the same instance as the one used to create the JTable

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Since you put the username, password at the query, it means that if the query returns then the username, password given were in the database. You don't need to get the username, password from the database and compare them again. This will do:

if (rs.next()) {
 // success
} else {
 numberOfAttempts++;
 if (numberOfAttempts>3) {
   // exit   
 }
}

You'd better try to understand the code I give you and not just copy paste it

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

When you have a form with a servlet you have sth like that:

<form action="someServlet">
  ... data to be sent
</form>

For a link:

<%
String name = "a";
String pass = "a";
%>

<a href="someServlet?[B]name[/B]=<%=name%>&[B]password[/B]=<%=pass%>">
  Click Me!
</a>

Instead of <%=name%> you can have whatever you want:

<a href="someServlet?[B]name[/B]=1111&[B]password[/B]=2222">
  Click Me!
</a>

Or you can have more:
"someServlet?req1=111&req=2&req3=3&req4=4"

And at the servlet get them like this:

request.getParameter("[B]name[/B]");
request.getParameter("[B]password[/B]");
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

I had checked the Sun tutorial but still stuck... i'm now trying to figure out the getSelectedValue mentioned in the first post...

In that tutorial there is this code:

String petName = (String)cb.getSelectedItem();

Where cb is the JComboBox. In the tutorial that piece of code is called whenever the comboBox is clicked, but you can call that method whenever you want. When you click the button call that method.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Look at API for the class JComboBox. There is a method called: getSelectedValue or something like that. It returns an Object. You can use that to get what is selected.
If what is added in the ComboBoxes are Strings then you can cast the result of the above method to a String.

You can have one button. Once clicked read the values from all comboBoxes

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

As I said in previous post, don't create a ResultSet and leave it open.
Have an object like this:

class Patient {
  private int patientNo;
  private String fName = "";
  private String lName = "";
.....

  public Patient() {

  }

 // have methods for getting, setting those values:
 public int getPatientNo() {
    return patientNo;
  }

 public void getPatientNo(int patNo) {
    this.patientNo = patNo;
  }
}

Then have a method like this:

public Patient getPatient(int patientNo) throws SQLException {
  // do the things I told you in your other post about how to read data from DataBase

  // if results found create a Patient object and return it
}

Then call the above method, get the Patient objetc and get its values. Then you can do whatever you want with those values.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Becuase you do this:

while(rs.next()) {
  if (success) {
     show page
  } else {
     error
  }
}

If you give wrong credentials the error message will be printed many times since it is inside a loop. Assuming that you have many entries in the database and only one matches the values you entered. When you reach the row that has the same "username", "password" entered the patient gui will be displayed but the while will continuing looping.

I already told you the right way to do things and you didn't follow them. If you are such a beginer that you can't even create a single method that returns true or false:

Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
//open connection
//create statement
//run query that returns ResultSet

//get the data from ResultSet
while(rs.next()) {
  if ( rs.getString("username").equals(username)  &&    rs.getString("password").equals(password) ) {
     return true;
  }
}
return false;
} catch (Exception e) {
    throw e;
} finally {
   if (conn!=null) conn.close;
   // the same for st, rs
}

Or can't even write a query such as this:

public boolean validate(String user, String pass) {
  String query = "select username, password from LoginTable where  username = '" + user + "' and password = '" + pass + "'";
}

Or follow this simple structure:

// declare Connection, Statement, ResultSet
try {
// Initialize Connection, Statement, ResultSet
} catch (Exception e) {
    throw e;
} finally {
   // close Connection, …
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

First of all you need to close the connection, statement and resultSet every time after you have used them.
Second try to print the stack trace of the exception. (e.printStacktrace()). And try to find at which line of the class you get that exception. If it is a NullPointerException, which probably is, it means that you are using something which is null, that you haven't initialized.

And have a seperate class that does the database handling. Have a seperate method that does this:

Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
open connection
create statement
run query that returns ResultSet
get the data from ResultSet
return;
} catch (Exception e) {
    throw e;
} finally {
   if (conn!=null) conn.close;
   // the same for st, rs
}
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Yes I could

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

All I would do is create a separate thread and start it whenever I want:

class MyThread extends Thread {

}
MyThread mt = new MyThread();
mt.start();

Now in the run method you can try something like this:

int count = 0;
while (count<10) {
  try {
     Thread.sleeep(1000);
     // beep;
  } catch (Exception e) {
  }
  count++;
}

Since the while repeats every 1 second, you can use the "count" variable to count 10 seconds.

Or you can use the "System.currentTimeMillis()" method to get the time in milliseconds and save it into a variable.
At the while statement compare that variable with the currentTimeMillis taken each time and if their difference is more than 10 seconds (10000 millis) then stop the loop

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Also you are making the same mistake you did in your initial post.
Remember, in order to print the text value of the node you are using this method:

System.out.println(node.getNodeName() + ":" + node.[B]getTextContent()[/B]);

So why are using this: node.setNodeValue("") in order to change its value?

Use the equivalent setTextContent("") method.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Use the equals method to compare Strings:

if ( ht.equals("h") ) {

}

Also you don't need to declare your integers Integer. Simple int will suffice:

int x=8,y=1,heads=0,tails=0;
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Also a good way to find out what type of node you have is this:

public static void main(String[] args) {
        System.out.println("ATTRIBUTE_NODE             :"+Node.ATTRIBUTE_NODE);
        System.out.println("CDATA_SECTION_NODE         :"+Node.CDATA_SECTION_NODE);
        System.out.println("COMMENT_NODE               :"+Node.COMMENT_NODE);
        System.out.println("DOCUMENT_FRAGMENT_NODE     :"+Node.DOCUMENT_FRAGMENT_NODE);
        System.out.println("DOCUMENT_NODE              :"+Node.DOCUMENT_NODE);
        System.out.println("DOCUMENT_TYPE_NODE         :"+Node.DOCUMENT_TYPE_NODE);
        System.out.println("ELEMENT_NODE               :"+Node.ELEMENT_NODE);
        System.out.println("ENTITY_NODE                :"+Node.ENTITY_NODE);
        System.out.println("ENTITY_REFERENCE_NODE      :"+Node.ENTITY_REFERENCE_NODE);
        System.out.println("NOTATION_NODE              :"+Node.NOTATION_NODE);
        System.out.println("PROCESSING_INSTRUCTION_NODE:"+Node.PROCESSING_INSTRUCTION_NODE);
        System.out.println("TEXT_NODE                  :"+Node.TEXT_NODE);
        /*
        System.out.println("DOCUMENT_POSITION_CONTAINED_BY:"+Node.DOCUMENT_POSITION_CONTAINED_BY);
        System.out.println("DOCUMENT_POSITION_CONTAINS:"+Node.DOCUMENT_POSITION_CONTAINS);
        System.out.println("DOCUMENT_POSITION_DISCONNECTED:"+Node.DOCUMENT_POSITION_DISCONNECTED);
        System.out.println("DOCUMENT_POSITION_FOLLOWING:"+Node.DOCUMENT_POSITION_FOLLOWING);
        System.out.println("DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC:"+Node.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC);
        System.out.println("DOCUMENT_POSITION_PRECEDING:"+Node.DOCUMENT_POSITION_PRECEDING);
        */
    }
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

First of all here is a small misconception:
This:

<VERSION>3.1</VERSION>
<SMTPSRV>blue</SMTPSRV>

is not Two nodes but Three!

Node 1:
<VERSION>3.1</VERSION>

Node 3:
<SMTPSRV>blue</SMTPSRV>

Node 2:

<VERSION>3.1</VERSION>
<SMTPSRV>blue</SMTPSRV>

The new line character between </VERSION> and <SMTPSRV>

So when you print this: System.out.println(node.getNodeName() + ":" + node.getNodeValue()); For Node <VERSION>3.1</VERSION> :
You have Name = VERSION,
Value is null, because <VERSION> doesn't have a value

And for the new line:
Name: Doesn't have a name because it is just text in the file so you get #text
Value: you get the new line character, which is why you get that empty line.

Try printing this:

System.out.println(node.getNodeName() +":"+([B]node.getNodeType()[/B]==Node.TEXT_NODE)
+":"+[B]node.getNodeType()[/B]);

You will see the it is true only for the #text, and for the nodes whose values you want is >1<

So you can do this to avoid the free text that is between the nodes in your file:

<VERSION>3.1</VERSION> [B]<new line>[/B]
[B]<some spaces>[/B]<SMTPSRV>blue</SMTPSRV>
       <SMTPPORT>29</SMTPPORT>
if (node.getNodeType()==Node.ELEMENT_NODE) {
   System.out.println(node.getNodeName() +":" + node.[B]getTextContent()[/B]);
}
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

You need to have an upper limit for the channels. Declare it as a constant in the TVRemote class.

When you try to increase the channel above that limit then have channel become 1. When you try to decrease it below 1 have channel take the upper limit.

The same as volume you should have code that checks if the volume has gone below 0 and prevent that. May be ignore it or print a message:

public void decreaseVolume() {
   if (volume==0) {
     // cannot decrease;
   } else {
      volume--;
   }
}

Also you should have checks at your set methods:

public void setChannel(int a) {
   if (a<1) {
      channel = 1;
   } else if (a>TOP_LIMIT) {
     channel = TOP_LIMIT;
   } else {
      channel = a;
   }
}
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

First of all you have some spaces at the query that will not get you right results: "select * from members where username = ' "+username+" ' " Should be: "select * from members where username = '"+username+"' " Second: the "ResultSet" is the name of the class and the "username" is a String variable. Shouldn't you focusing more on learning simpler things, because form what I see from your code, what you are trying to achieve is way above your skills. You don't even know how to compare 2 variables or use class instances and you are trying to write a login page?

Anyway, first check the API for the ResultSet. There you will find methods that will help you extract the data from the ResultSet object. Better yet search this forum for examples on how to read data from the database.

As for your query it is better instead of this "*" to put the actual columns: "select username, password from members where username = '"+username+"' " Then take the username, password from the ResultSet and compare it with what you get from the GUI

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

The error is pretty obvious and has nothing to do with sql:

unreported exception java.sql.SQLException; must be caught or declared to be thrown

You are calling a method that throws an exception, and you don't catch it.
I mean why did you surround the DriverManager.getConnection with a try-catch?

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

I can write this code but I can't Complete it

As masijade said post what you have done so far and we will see what we can do for you.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

A Driver class is nothing special. It's just a name, and it means the class in which we call all our methods. The class with the main method that we call in order to run the application.

class Methods {
  public static int add(int a, int b) {
    return a+b;
  }
  public static int sub(int a, int b) {
    return a-b;
  }
}

class MainDriver {
  public static void main(String [] args) {
      // read from the keyboard or the arguments 2 numbers:
     int a = 5;
     int b = 6;
     int c = Methods.add(a, b);
     System.out.println(c);

     int d = Methods.sub(a, b);
     System.out.println(d);
  }
}

Try to avoid declaring methods in the driver class. Just have the main and call whatever you need in the main in order to run your application.
That will include initializing objects and calling their methods:

class Person {
  public String name = "";
  public int age = "";

   public Person() {

  } 

  public Person(String n, int a) {
   name = n;
    age = a;
  }
}

class MainDriver {
  public static void main(String [] args) {
      Person p1 = new Person();
    p1.age = 12;
   p1.name = "Name 1"

   Person p2 = new Person("Name 2", 10);

System.out.println(......);
System.out.println(......);
  }
}

You have your Person class and in order to test it, you created a "driver" class with a main method.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster
for (int i = 0; i < adj2.length; i++) {
				for (int j = 0; j < adj2.length; j++) {
					path += [B]adj[i][j]*adj[j][i][/B];
}
}

The above always returns 0. If you run the code by hand you will see that the above snippet, never has 2 elements that this happens: 1*1 . Try a different initial array.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster
public class ArithmeticOperatorImpl implements ArithmeticOperator {
  ....
}
public class OpIterator implements OperatorIterator {
  ....
}

Then create the OperatorFactory class that creates ArithmeticOperatorImpl objects and returns them based on the input

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Manual. Gives full control with no "bolierplate", repetitive, rigid code.

But that's not what you're looking for is it? I dislike all "Gui builders", as they all produce rigid, reptitive code that is hard to modify correctly, and is not always that effecient when any action to be performed is more than popping up a dialog.

I agree. I prefer to write my own gui.

Surely I also use a Gui Builder but just to quickly declare and place the elements.

But most of the times I do them on my own.
It is hard to use a gui builder to create dynamically a list of buttons or a ComboBox whose values are generated by some other function.

It is better to learn how to create JFrames on your own and not depend on a builder. Especially for actionListeners. The code that they generate is not easy to follow and you won't learn how they work and called.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

You haven't described what is your problem and what have you done so far. Don't expect us to read the entire code and see what works and what doesn't.
Also you are mixing everything up.

Forget about the gui.
Keep the node class and create an AVLTree class. The Tree is not a gui and has nothing to do with is. It is a tree. Meaning, test the functionality of the tree separately. The tree will do only the things you described. Have methods with arguments that search and delete and test all of them using System.out.print in a separate class. That class will have only the main method. Instantiate the tree in the main method and test it. Then create another gui class and this time instantiate the tree in there and use its methods.

That way if something doesn't work you will know what it is.

With your description and code no one is going to understand what is your problem. If your problem is for example "preorder" then all you have to do is fix the specific method and test it separately in the main method that I described. If it works, in the same main you will test the rest of the methods.
Then if all of them work you will call the Tree class in the new gui class that you will create and all other errors that you will be getting will be gui related. So you will …

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Use a for loop, to loop through the ArrayList and print its elements instead of the System.out.println(row1)

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

You said I do not need casting but I am having trouble putting the subclass object variables into the musicArray. I read last night that this is because I have to upcast to the parent object.

I ran this:

Music [] array = new Music[3]; // array is an array and it is not null

        // Its elements are so you need to initalize them
        array[0] = new RockSong();
        array[1] = new ClassicalPiece();
        array[2] = new Music();
        // array[0], array[1], array[2] are Music

        for (int i=0;i<array.length;i++) {
           System.out.println(array[i]);
        }

And it worked.
For the other way around you need "down casting", after checking of course if it can be done with the "instanceof"

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

After taking a closer look at the code you don't need the casting. Since you read from the file a Music object, it doesn't matter what type of music it is:

while (true) {
     Music music = (Music)inFile.readObject();
     musicArray[count] = music;
     System.out.println(count+": "+musicArray[count]);
     count++;
}

Also I would suggest to put the EOFException inside the while loop.

while (true) {
     try {

     } catch (EOFException eofe) {
         break;
     }
}

Leave the rest of the exceptions outside. With that way you will exit the loop once you are done reading the file and then you can do whatever you want with the array, without having to end the program.
Then after the while loop through the array and print its elements

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Even though from your code you have figured out on your own how to use array of objects here is a small example:

Music [] array = new Music[3]; // array is an array and it is not null

// Its elements are so you need to initalize them
array[0] = new RockSong();
array[1] = new ClassicalPiece();
array[2] = new Musical();
// array[0], array[1], array[2] are Music

for (int i=0;i<array.length;i++) {
   if  (array[i] instanceof RockSong){
        RockSong rs = (RockSong)array[i]; // this is how you cast
  } else ...
}

Now as far as the rest of your code:

This is an endless loop because you don't specify when to stop, nor you know the end of the file or how many Music objects are in the file.

while (true)
{
    Music music = (Music)inFile.readObject();

I don't know what will the method do if there are no more objects. Maybe that is why you are getting a NullPointerException. Try to print what you get as soon you read the file and try it with a small file that has only 2 objects

Second, What is the format of the file. I mean how were the objects serialized?


Also here a suggestion depending on your requirements.
Another way for the file to have more than one Music objects then why don't you serialize a Vector:

Vector<Music> v = new Vector<Music>();

v.add(new RockSong());
v.add(new ClassicalPiece());
v.add(new Musical());

// serialize the Vector in the file.
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

The problem I am having is getting the out of bounds exception to work without calling either of the other two catches.

I don't really get the above, but I have a few corrections to add.

First, don't use the toString method of the exception. Use the getMessage to print the error.

String output2 = "Incorrect datatype entered for textfield 2\n" +
"Occured after pressing enter in the 1st textfield\n" +
"Enter appropriate datatype\n" + ex2.getMessage();

And secondly whenever you catch an exception, you print the error and then you continue with the execution of the program. If an exception occurred (user entered non numeric) you shouldn't continue with the rest of the program. So I would suggest to put a return statement at the end of each catch:

catch (Exception ob) {
                    String output2 = "Index is out of bounds\n" +
                            "Exception occured after pressing enter in the first textfield\n" +
                            "Re-enter a selection in the range of " + MIN_INDEX + " - " + MAX_INDEX;
                    ob.toString();
                    JOptionPane.showMessageDialog(null, output2);

[B]return;[/B]
                }
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

The split returns an array. And you try to cast it to ArrayList.
From the String get the String [] array using the split method.
Then loop through the array and add its elements to an ArrayList

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

I think you should keep your code they way it was and return the index where the target element was found. Without increasing it by 1. In your methods you should always return indexes the way they are. 0 based. In java indexes begin with zero. Don't change that. If you want to add 1 do it after your program returns the value when you print int.

Not to talk about your problem. Keep the code the way it is and find the index where the target is. Then outside the while loop, after you get the index, search the neighbor elements to see if they are equal with the target.
First start checking the ones that are lower than the index and keep reducing the index until you find something that is not equal:

int index;
while () {

}
// found target at index
int tempIndex = index;
while ( ([B]tempIndex>=0[/B]) && (userArray[tempIndex]==target) ) {
  System.out.println("Found at: "+tempIndex);
  tempIndex[B]--[/B];
}

// do the same by increasing the index. Careful with the expression at the while loop

All it is left to decide now is what you want your method to return and how.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

So i cant say this in the main method? .....
isItPrimeorNot = isPrime(num);

Sorry im new to Java. (:

You can make the method static. Like the main.

GTJava commented: Very helpful! +1