javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Another thing that I would like to add, that might not be clear. That code using the ObjectOutputStream and ObjectInputStream, is best used to save whole objects. Not only int numbers: out.writeInt(1) If you look at the API, there is a method: ObjectOutputStream.writeObject(Object obj) that takes as argument any object. So if you have a class with many attributes, you can call only that method and that's it.
For reading just call: ObjectInputStream.readObject() . It returns an Object and all you have to do is cast to the right one.
These classes have examples:
ObjectOutputStream
ObjectInputStream

Remember in order to do that, the class that you are trying to save must implement the Serializable interface. And if your class has other classes as attributes, those must also implement that interface:

class CustomObject1 implements java.io.Serializable {
    private CustomObject2 cust = null;
    private String s = null;
    private int i = 0;
}
class CustomObject2 implements java.io.Serializable {

}

If you look at the API of String class you will see that it already implements that interface. And primitive types "int" can be written with no extra work. So you are good to go.
That means that not all classes of the JAVA API can be written with that way if they don't implement Serializable.

You can write collections as well:

SomeObject [] array = new SomeObject[5];
....
....

File f = new File("filename");
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(f)); …
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Inside the overridden method use code that checks the color. If it is purple, don't change it

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Since vchandra has already answered your question, I would like to add that any class that implements the Comparable interface can be sorted using the compareTo method. If you look at the API the String class implements the Comparable, so it has a "compareTo" method that you can call.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

What kind of data, you want to save and do you have any "homework" restrictions concerning how the data will be saved?

There is the easy way using the Serializable interface. The code is only a few lines, but you will not learn much.

And the hard way would be to write the values of the attributes of your classes to a text file. With this way you will learn how to write and read from files.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Assuming that you are using java 1.5 or later then:

public class SomeObject implements Comparable<SomeObject> {
    

     public boolean equals(Object obj) {
         if (obj==null) return false;
         if (obj instanceof SomeObject) {
               SomeObject so = (SomeObject)obj;
               // write your code here that compares the values of the so attributes with the attributes of this class.
         }
         return false;
     }

     public int compareTo(SomeObject o) {
          // look at the API of the Comparable interface. It explains how this method should be implemented.
     }
}
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Since you start the index from 0 the first loop would be this:

for (int i = 0; i < sides; i++)

If sides = 3, then i = 0,1,2. 3 sides.
Or:

for (int i = 1; i <= sides; i++)

If sides = 3, then i = 1,2,3. 3 sides.

As you have noticed you entered 3 and the program asked for 4 points.

Also it is not a good idea to have the methods of an object (Point, Line) to call the System.out.println. What if you want to use it in desktop gui, or a web page. You will have to make additional changes.
If you had methods that return values, you could use them anywhere you want:

class Point {
   int a = 0;
   int b = 0;

   public String toString() {
       return "("+a+","+b+")";
   }
}
class Line {
   Point p1,p2;

   public Point getP1() {
      return p1;
  }

   public double length() {
       // calculate length;
       return 123.45;
   }
}
System.out.println("Point 1: "+ L1.getP1());
System.out.println("Point 2: "+ L1.getP2());
System.out.println("The length of the line is: "+ L1.length());

Now that you have the length, you can add all the lengths in the for loop:

[B]double sum = 0;[/B]
for (int i = 0; i < pointsArray.size() - 1; i++)
{
// YOUR CODE
   Point P1 = (Point) pointsArray.get(i);
   ...
   System.out.println("The length of the line is: "+ L1.length());

[B]sum = sum + L1.length();[/B]
}
[B]System.out.println("Perimeter: "+sum);[/B]
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Have you tried reading the errors that you get? Because If you had the solution would be very easy:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at Transfer.actionPerformed(Transfer.java:111)

You get a NullPointerException at the Transfer.java file, at the actionPerformed method at line 111.

You are using something which is null. Initialize it.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

I believe the set and get methods are used for code reusability...?

This is what happens when I try to run the program.

Please enter radius of circle:4
The radius of the circle is
Exception in thread "main" java.util.IllegalFormatConversionException: d != java
.lang.Double
at java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:399
2)
at java.util.Formatter$FormatSpecifier.printInteger(Formatter.java:2708)
at java.util.Formatter$FormatSpecifier.print(Formatter.java:2660)
at java.util.Formatter.format(Formatter.java:2432)
at java.io.PrintStream.format(PrintStream.java:920)
at java.io.PrintStream.printf(PrintStream.java:821)
at Circles.displayMessage(Circles.java:29)
at CirclesTest.main(CirclesTest.java:23)
Press any key to continue...

The stack trace tells you exactly where the error is. It would be helpful next time to read it and if you can't fix it, to point where that line is at the code you posted.

Exception in thread "main" java.util.IllegalFormatConversionException: d != java
.lang.Double

at java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:399
2)
at java.util.Formatter$FormatSpecifier.printInteger(Formatter.java:2708)
at java.util.Formatter$FormatSpecifier.print(Formatter.java:2660)
at java.util.Formatter.format(Formatter.java:2432)
at java.io.PrintStream.format(PrintStream.java:920)
at java.io.PrintStream.printf(PrintStream.java:821)
at Circles.displayMessage(Circles.java:29)
at CirclesTest.main(CirclesTest.java:23)

The error is at the displayMessage method of the Circles.java file at line 29.

The getRadius method returns Double, which is an object. The printf method: "The radius of the circle is \n%d!\n"
expects a double primitive type.

So I think that if you change the return type of the getRadius method to double should correct your problem.
It is better, when you create get/set methods, to have the argument of the "set" and the return type of the "get" to be exactly the same type as the variable used.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Post your error messages.

Also you have a method: setRadius
Why don't you use that instead of this: myCircles.radius = input.nextDouble()
What's the point of having it?

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster
{
// piggy is NULL
this.piggy.setColour(Colour.PINK); // error

// piggy is NULL
this.piggy.setPosition(0); // error

// now you give piggy value.
this.piggy = aPig;
}

First you give value to an object or create it and then you use its methods

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

You throw it, but you don't catch it. Exceptions tend to terminate your program in a bad way. You need to catch them so that it won't terminate your program:

public static void main(String args[]) {
A a = new A();
int x1;
int x2;
x1 = 7;
x2 = 0;
  try {
     a.printer(x1, x2);
  } catch (ArithmeticException ae) {
     System.out.println("An error occured: "+ar.getMessage());
  }
}
System.out.println("Finishing the program");
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

I already explained the the piggy attribute is null because you never set its value, with the argument of the constructor:

public class Animal
private Pig piggy;
private int reset;
private int position;

/*Constructor of the object Animal*/
public Animal(Pig aPig) {
this.position = 0;
this.reset = 0;
piggy = aPig
}

public void resetCount()
{
 // do whatever the assignment says
 // change the position
 pig.setPosition(0);
 // change the color
 pig.setColour(Colour.PINK);
}
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

print display the following message...

An instance of class Pig: position 1, colour Colour.RED.

When it should really be in position 0, colour PINK.

Can you post the latest code of what you can post.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

when you say print the value method do you mean println, I am using graphical objects. The actual work I am doing is different. I don't really want to give the whole code out. I will check on the return value of the getPosition.

It doesn't matter. The print is for debugging just for you to see what value it has, in order to understand what is going on.
And yes I mean: System.out.print....

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

thanks for the quick reply..really appreciate it but i have some doubts ..can u pls help me out

public void method(File dir) {

do i pass my root directory over here..

That method gets all the Files under the input directory. If it is a text file then it reads it, if it is a folder then it calls it self in order to read the Files under that directory.

Look at the code. With what was given it is up to you to understand it

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

First of all always use {} brackets. Look what you wrote:

if(arg == "Exit")
 System.out.println("Program Terminated.");
 System.exit(0);

And what I wrote:

if(arg == "Exit") {
 System.out.println("Program Terminated.");
 System.exit(0);
}

In your first code, if the if statement is true it will execute only the System.out.println("Program Terminated.") and the System.exit(0) will always be executed, because you didn't put ant brackets.

And I would suggest not to use this:

String arg = e.getActionCommand();

 if(arg == "NewGrades") {

}

But this:

public void actionPerformed(ActionEvent e)
{ 
   Object src = e.getSource();

   if (mnuFileNewGrades == src) {
      // ....
  } else if (mnuFileExit == src) {
     System.out.println("Program Terminated.");
     System.exit(0);
  }
}
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

First of all don't use the list() method because it doesn't return the full path and you forced to do this:

String NewDir = dirLocation +"\\"+filename;

Try this:

public void method(File dir) {

File [] children = dir.listFiles(); 

for (int i=0;i<children.length;i++) {
   if (children[i].isFile()) {
       BufferedReader reader = null;
       try {
              // read the file
              reader = ...;
       } catch (Exception e) {
            System.out.println(e.getMessage());
       } finally {
            try {
               close(); // close the readers you used to read the file (BufferedReader and so on)
           } catch (Exception e) {}
       }
   } else if (children[i].isDirectory()) {
             method(children[i]); // recursive call
   }
}

}

You can also check if the file is a .txt file before reading it:

public isTxt(File file) {

String name = file.toString();
int length = name.length;

if (length<=3) return false;

return name.subString(length-3, length).equalsIgnoreCase("txt");
}

And next time use code tags. Press the (code) button when creating a new post.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

like that it will not set the file path correctly.
so instead of
File inuse = new File(temp)
you need to write
File inuse = new File("c:\\test\\"+temp)
cheers

vchandra is right.

Also it is a good thing always to check the API of the classes you are using. Why did you assumed that the dir.list() method returns what you want. If you had looked the API you would have seen that it doesn't return the full path.
You could also see this other method that does what you want:

File [] children = dir.listFiles();

You could have used that instead that returns the full path of the file.

Also whenever you are having problems you can print the values of what you are using:

// -->
System.out.println("Deleting: "+inuse);

boolean success =	inuse.delete();

You would have seen that the "inuse" file is not the right file.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Then print the value of the method. You say that the if doesn't work, but do you know what value does the getPosition() returns?

Also post your entire code using code tags. Press the (code) button when creating a post and put code inside.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

First of all the this.pig is null. You declare it as attribute at the class but you never give it value. You need to pass the parameter of the constructor to it:

public Amplifier(Pig aPig)
{
   this.pig = aPig;
   this.number.resetCount = 0;
}

Also in the reset method you check for the position but you never change it. If this.pig.getPosition() is greater than 1 then you will enter the loop, the color will change but you don't change the position. So the expression: this.pig.getPosition() > 1 will not change and you will never exit the loop.
Better try an if statement and change both these values to 0 and pink. Also there is a difference between saying: > 1 and >=1

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

This code: private Employee e = new Employee("ME","MYSSN"); calls the constructor.

public class Employee {
	
[B]	private Employee e = new Employee("ME","MYSSN");[/B]
	
	public Employee(Employee e){
		this(e.name,e.SSN);
		
	}

When the constructor of a class is called you create an instance of that class and its attributes are declared and/or initialized.
Meaning that when you do this: private Employee e = new Employee("ME","MYSSN"); you call the constructor that creates a new instance. When you do that the e attribute of the class is created and it calls this: private Employee e = new Employee("ME","MYSSN"); . When you do that the e attribute of the class is created and it calls this: private Employee e = new Employee("ME","MYSSN"); When you do that the e attribute of the class is created and it calls this: private Employee e = new Employee("ME","MYSSN"); When you do that the e attribute of the class is created and it calls this: private Employee e = new Employee("ME","MYSSN"); When you do that the e attribute of the class is created and it calls this: private Employee e = new Employee("ME","MYSSN"); So after a while when you create an instance you call this: ( private Employee e = new Employee("ME","MYSSN"); ) That piece of code creates another instance that calls the private Employee e = new Employee("ME","MYSSN"); which creates another instance, ...

So remove the private Employee e = new Employee("ME","MYSSN"); from the code

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Are you getting compile error?
I am not familiar with C#, but If we assume that the concatenation works the same then maybe this is the problem:

This:

<script type="text/javascript" src="<%=ResolveUrl"jquery.js"%>"></script> 
<script type="text/javascript" src="<%=ResolveUrl"JScript.js"%>"></script>

Should be like this:

<script type="text/javascript" src="<%=ResolveUrl + "jquery.js"%>"></script> 
<script type="text/javascript" src="<%=ResolveUrl + "JScript.js"%>"></script>

If it doesn't solve your problem then sorry.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Try to print it and then run it to an sql client or an sql editor and see what is the problem:

..
String query = "INSERT INTO WeatherHistory (Date, Location, Overview, Temperature, WindDirection, WindSpeed, Pressure) VALUES ('"+date+"','"+location+"','"+temp+"','"+windDir+"','"+windSpd+"','"+pressure+"')";

System.put.println(query);

prepStat = connection.prepareStatement(query);

Take what is printed and run it. Also you can post it here with the values that you entered.

The above are for general debugging in case you have any future errors. After looking at the query, I would like to ask:

The Date column, what type is it? Is it type VARCHAR2 or type DATE. If it is type DATE then I don't think that this would work: ('"+date+"', Also, and I don't know if it is a problem or not, I believe that "date" is a reserved word for the sql and you cannot use it to name columns. If that is the problem, you can try to rename it to weather_history_date

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

try this

public class Battleship{
public static void main(String[] args){
int boardInput = Integer.parseInt(args[0]);
}
}

Cheers

That is correct, but I would prefer something like this:

public class Battleship{

public static void main(String[] args){
    if (args.length>0) {
         int boardInput = Integer.parseInt(args[0]);
    } else {
         System.out.println("No arguments given");
    }
}

}

After you understand the above and get familiar with exceptions then try this in case the argument is not a number.

public class Battleship{

public static void main(String[] args){
    if (args.length>0) {

          try {
              int boardInput = Integer.parseInt(args[0]);
          } catch(NumberFormatException nfe) {
              System.out.println("No number was given: "+args[0]);
          }

    } else {
         System.out.println("No arguments given");
    }
}

}
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

This '%' gives the remainder of a number. An even number is the one that can devided by 2 so the remainder of 2 should be 0:

if (number%2==0) {
   System.out.println("Number: "+number + " is even.");
}
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

The link can be:

<a href="somepage.jsp?param1=aaaaa&param2=3333&param3=123">Link 3</a>

And at the somepage.jsp, you can do this:

String a1 = request.getParameter("param1"); // aaaaa
String a2 = request.getParameter("param2"); // 3333
String a3 = request.getParameter("param3"); // 123
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

In the same way you do it in any other class with any other object.
In one class make that object as a global attribute and either set it to be public or use get/set methods.

public class OneFrame {
  public SomeObject so = null;
  // create it in this class and do things with it

  public OneFrame() {
    so = new SomeObject();
  }
}

Since you didn't explain your problem very well, I am going to assume that when you click a button in this frame another opens and you want that object to be passed to the other frame?
Then at the second frame have the constructor take as parameter that object and pass the one you have at first frame as parameter.

public class OneFrame {
  public SomeObject so = null;
  // create it in this class and do things with it

  public OneFrame() {
    so = new SomeObject();
  }

  private void openNewFrame() {
    NewFrame nf = new NewFrame(so);
  }
}
public class NewFrame{
  public SomeObject so = null;

  public NewFrame(SomeObject so) {
    this.so = so;
  }
}
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Take a look at your brackets. Always use them. You are suppose first to check the input and then calculate:

for () {
  if (not a digit) {
      return false;
  }
}

// if the above code didn't return then the input is OK

But you do this:

for () 
  if (not a digit) {
     return false;
  } else {
      // calculate;
  }

Since you didn't put brackets at the for-loop it will loop the next command which is not the "if" statement, but the "if-else" statement. The above code that you wrote is actually this:

for () {
  if (not a digit) {
     return false;
  } else {
      // calculate;
  }
}

Meaning that calculate is inside the for-loop. Meaning that you will check each digit but do the calculation anyway:
IF input is: "a1"
The the "a" is not a digit, so the code will exit.
But when you enter: "1a", the "1" is a digit so it will go at the else, which will do the calculate and give you an error.
So always use brackets even for single commands and use the first code that I posted.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Hey, thanks! I'm not up to speed with the classes you've used or with coding for exceptions, but I'll go through the API and see what I can learn… Thanks again.

Oh, another quick question… are the methods and constructors given in the API specific enough? I shouldn't run into any issues if I stick with those right?

The API is the official reference. This is where you needto look. It explains exactly what are the arguments of a method/constructor and what they return and most importantly what they do exactly. So don't assume that you know what a method does, just read the API for a more detailed description.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

i think you have not extended the taxpayer class from other main method class and also the both classes shud be in same package

You couldn't be more wrong. Please don't give wrong advices if you don't know what you are talking about.

Do all Social-Security-Numbers(SSN) need to be like this: (111...111, 222....222, ...) ?
Since you can have 999999999 different combinations, why do you want to limit yourself by using only those, when you can do this:

for (x = 0; x < 10; ++x)
	{
	somePayer[x] = new Taxpayer((x+1), 0.0);

}

The above will print:
1
2
3
4
....

If you want them to be:
000000001
000000002
000000003
000000004
Then don't use an int variable, use a String. Ints are used for calculations and you are not going to do any addittions with the SSN.
So this is my suggestion:

//Date: 3/18/2010

public class Taxpayer 
{
	private String socSec;
	private double yearlyGross;
	
	public Taxpayer(int taxPayer, double income) 
	{
		convertToString(taxPayer);
		yearlyGross = income;
	}
	public String getSocSec()
	{
		return socSec;
	}
	public double getYearlyGross()
	{
		return yearlyGross;
	}

       private convertToString(int i) {
           socSec = String.valueOf(i);

           while (socSec.length()<9) {
                   socSec = "0"+socSec;
           }
       }
}

In that wat when you call the constructor with an int: 1, then it will become the Stirng "0000000001"

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

It looks like it should work but have you tested it? Also you will need to take each element of the array and check if it is between 1-12 and 1-31. You should also check depending on the month if it has the irght number of days. (April cannot have 31 days). Also depending on the year and the month you might want to check if February has the right nunmer of days.

For validating String that represent dates better use this:

SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yy");
sdf.setLenient(false);

String input = "something";
try {
   Date d = sdf.parse(input); // if the string is not a dd-MM-yy date it will throw an exception

   this.date = input;
} catch (ParseException e) {
  // error
  this.date = "00-00-00"
}
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Use BufferedWriter that takes argument a FileWriter. Check their API

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Since this is your exam it means that you attended a whole semester of your java course. Surely you would know how to create classes with attributes.

Well the instructions are pretty clear:

Create a Class
.....
EmployeePay (parent)
define: attribute: salary(net), gross, rate, no of hours worked, tax=20%
constructor: (2)

You would advise you to follow them

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Because 'a' and 'b' don't have the same length:

for (int i = a.length-1; i >=0; i--){
   sum = a[i] + b[i]+ diff;
}

At the above code you check only if the 'i' will be able to be applied at the 'a' array. But you don't check the length of the 'b' array.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Inside the cases of the do-while you set goOn to false. So you will exit the while-loop:

..
case 1:
  myAccount.deposit();
  goOn = false;
  break;
..

} while (goOn == true);
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

This is the problem

if(ah.hasNextDouble())[B];[/B]

When you add the ; it ends the command. Meaning that you ended the if command. Meaning that the rest:

{

}

Weren't "connected" with the if. It was like writing this:

if(ah.hasNextDouble()) { 
}

{
w=ah.nextDouble();
 x=ah.nextDouble();
 y=ah.nextDouble();
....
}
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Check the API for the PrepareStatement class. There is something called: setNull(int, int) . The first argument is the index of the '?' and the other the type of the column.

Assuming that col2 is type of NUMBER at your database table then you can do this:

pstmt.setNull(2, java.sql.Types.NUMERIC)

instead of this:

//pstmt.setInt(2,null);

http://java.sun.com/j2se/1.4.2/docs/api/java/sql/PreparedStatement.html#setNull%28int,%20int%29

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Have you considered using:
while(hasNextDouble)

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

The while takes as "argument" a boolean expression. So why don't you use a boolean.
At first have it to be true, so you will enter the loop. If the user enters correct String that can be converted into a number, meaning that this: Integer.parseInt will execute, make that variable false. That will make the loop exit

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

It's actually quite ridiculous my code snippet got voted down twice the other day also -- I think it's just incompetent users randomly voting things down they don't immediately understand because they are java noobs. I don't think it's something to really worry about. And... I'm guessing this post will be voted down too ;)

I don't believe it is because they don't understand the code, but simply because they are just bad and mean. But I will have to agree with the randomness thing.

Also since this is getting way out of topic I suggest we stop here discussing about it. At the DaniWeb Community Feedback forum there is a thread there you can contribute.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Ok this is serious and somebody should do something about it. I just saw that need, the poster who created this thread got down voted, twice!

I would like the @#!@$!@$# that did this to post here and explain the reasons. Because people get down voted for no reasons when they have very good posts, or posts that violate no rules, such as this one.

Why was the fist post down voted?? Are you man enough to show yourself and explain why?

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

I would suggest to write a method that takes as arguments the array of Students and a Student object:

boolean static int indexOf(Strudent [] array, Strudent st) {
  
}

Loop the array and see if the array contains the Student st. If found, immediately return the index where that student is. If you finish the loop without returning, means that you didn't found the student, so return -1 at the end:

YOUR Code with mine:

//StudentTest
import java.util.Scanner;

public class StudentTest {
	public static void main( String[] args)
	{   
		Student[] students = new Student[2];
		Scanner inputs = new Scanner(System.in);
		for(int i = 0 ; i < students.length; i++)
	    { 
	       
	      System.out.println("Please enter Student Number");
	      String fName = inputs.nextLine(); 
	      System.out.println("Please enter Student First Name");
	      String lName = inputs.nextLine(); 
	      System.out.println("Please enter Student Last Name");
	      String sNumber = inputs.nextLine(); 
 
//        NEW CODE ///////////////
               Student st = new Student(fName, lName, sNumber);

               if (indexOf(students, st)==-1) {
                   // New Student
	           students[i] = new Student(fName, lName, sNumber);                    
              } else {
                    System.out.println("Student: "+st+", already exists");
                    i--;
              }
//        NEW CODE ///////////////

	}
		for(int i = 0 ; i < students.length; i++)
	    { 
		System.out.print(students[i].toString());
	}
	

}

boolean static int indexOf(Strudent [] array, Strudent st) {
    // TODO
}

}

Be careful in that method to make sure that you don't compare any null objects. The array when initialized has null values as elements, so I would suggest something like this: st.equals(array[i]); instead of array[i].equals(st); Also for the above comparison you must use the equals method. For that …

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Thanks so much !

Another thing i dont get is that the hashtable stores plane objects (dont ask) i wrote some code that iterates through the table, how can i access some of the variables for the plane object? i have get methods for it. Sorry this key thing confuses me.

Plane plane = new Plane();
Hashtable<String, Plane> table = new Hashtable<String, Plane>();
table.put("keyPlane1", plane);
....

Plane p = table.get("keyPlane1");
p.getName();
p.getSeats();
p.getNumberOfEngines();
...


table.get("keyPlane1").setName("Boing 777");

In case the you are using a key that doesn't exist in the table then you should always do this just in case:

Hashtable<String, Plane> table = new Hashtable<String, Plane>();
table.put("keyPlane1", plane);

Plane p = table.get("keyPlane2");
if (p==null) {
  System.out.println("keyPlane2 doesn't exist");
} else {
   system.out.println("Plane found: " + p);
}

Look at the API for Hashtable

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Are you saying that you saved the images to a file, then changed the class and then tried to read? If yes then Yes you will not be able to read them because:
You serialized instances of this: SerializableImage. the files containes this: SerializableImage.
But whan you read them you are trying to pass that to a: myPackage.SerializableImage instance.
This will compile:

myPackage.SerializableImage image = (myPackage.SerializableImage)readObject();

But if the read object doesn't return an myPackage.SerializableImage object the program will crash. And the files contain SerializableImage objects.

So you will have to serialize the images again. Or for a more "professional" solution: Write a prgram that reads all the files and saves them into a SerializableImage. Then use the values of those objects to create mypackage.SerializableImage objects and save those by replacing the old files. you will have to do the above only once and the files will work from now on.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

your should create your comparator class by implementing Comparator Interface.

Once you do it, then you can create your hashtable as follows:

private Hashtable<String, Planes> planesFlying = new Hashtable<String, Planes>(new YourMapComparator());

something similar to this.

That is COMPLETELY gangsta1903 wrong. If you don't know java don't give wrong advices. Where did you see that constructor:

private Hashtable<String, Planes> planesFlying = new Hashtable<String, Planes>(new YourMapComparator());

Here is the solution.
Do you want to sort this out based on the key (String) or the values (Planes)?

If you want it based on the key then look at the API for the Hashtable class. There should be a method that lets you take the keys as a collection (Set<K> keySet() ). Use the toArray method of that Set to create an array. Then you can use any algorithm you want or you can use the sort method of the java.util.Arrays. You don't need to implement the Comparable interface since the String class already does that.
After the array with the keys is sorted you can loop that array and use each key to get each plane from the Hashtable.

I would like also to add that it is not a good idea to to use Hashtable if you want them sorted. You'd better use a Vector to put your Planes and have the "key" as part of the Plane's class attribute. If you do that you will have to implement the Comparable class. Check the derscription of this:

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

we don't deliver custom made code ...
I provided you with some logic you could follow, if you know how to create a checkbox and how to work with arrays, you should be able to try that

He is right. When you run the query save the results in list or an array. Then loop that array and create with each loop a different checkbox. Then use those checkboxes in any way you want.

Also if you are using a GUI builder for your gui then it will not work for a variable number of checkboxes

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Never mind I found it. I usually come up with solution after I make posts that ask for more information.

Anyway, you need a way to find the type of a variable. As BestJewSinceJC has mentioned you can do this:

Object.getClass().getName();

But he said that will not work with primitives. Actually with a small trick, it will:

public String [B]type[/B](Object obj) {
   return obj.getClass().getName();
}

Now try to call it like this and see what happens:

Integer intgr = new Integer(10);
int i = 5;

System.out.println(intgr + " is: "+[B]type[/B](intgr));
System.out.println(i + " is: "+[B]type[/B](i));
stephen84s commented: Autoboxing, but honestly your post could be more clear on the fundamentals the solution uses. +5
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

hi everybody!!!!!!!
can anyone tell me how do we test the data type of variables in java, like if a variable is a string, the system prints out that this variable is string or not.
more especially how can we test this on primitive data type?

waiting for your replies!!!

Can you post the exact description of your problem? What are trying to accomplish and what have you been asked to do?

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

The program doesn't work because you haven't followed ny instructions:

public class ShapesPanel extends JPanel implements ActionListener {
  public ShapesPanel() {
      ....
      circle.addActionListener (this);
      square.addActionListener (this);
  }  


public void actionPerformed (ActionEvent event)
      { 	
		  		if (event.getSource() == circle)
        	 	{
..
				}
				
         	else
				{
				..
				}  
      }
}

ShapesPanel is the one that implements the ActionListener and that is the one that needs to implement the actionPerformed method and that class ( this ) would be the input to the addActionListener.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Look how you have defined the draw method in your Circle class, and how you are calling it.

About the "square1" error you have declared it correctly at the ShapesPanel class but you are using inside the private ButtonListener class.
Maybe you should do this:

public class ShapesPanel extends JPanel implements ActionListener {
  public ShapesPanel() {
      ....
      circle.addActionListener (this);
      square.addActionListener (this);
  }  


public void actionPerformed (ActionEvent event)
      { 	
		  		if (event.getSource() == circle)
        	 	{
			   	circle1.draw();
					circle2.draw();
				}
				
         	else
				{
					square1.draw();
					square2.draw();
				}  
      }
}