javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

No you need to have a finally because even if an exception occurs you will still need to close the PrintWriter. The error happens because you declare PrintWriter inside try {....} and in the finally it is out of scope, it cannot be used outside try because this is where it declared. Try this:

import java.io.*;
import java.util.*;

public class Streams {

	public static void main(String[] args) {
		String studentFirstName = "Bob ";
		String studentLastName = " Smith ";
		String finalGrade = "A";

		PrintWriter out = null;

		try {
			out = new PrintWriter(new FileOutputStream("Student.txt"));
			out.print(studentFirstName);
			out.println(studentLastName);
			out.print(finalGrade);
							
		}
		catch (IOException e) 	{
			System.out.println(e);
		}
		finally {
			if (out!=null) out.close(); //in case you have an exception before  PrintWriter takes value
		}
	}
}
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Math.random()

The above returns a random number between 0 and 1

a pseudorandom double greater than or equal to 0.0 and less than 1.0.

Math.random()

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Amazing, This code is really helpful.

It can be found in any book and tutorial. And I wrote this a long time ago, meaning that there are better versions of that

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Inside a class declare the variable:

Connection conn=null;

In the same class:

Method for opening connection. Uses the myssql driver. download the jar and add it to the jars of your project

protected void openConnection() throws Exception {
        if ((conn==null)||(conn.isClosed())) {

String ip = "10.23.14.5"; //the ip of the database, in your case it would be localhost
String db_name="name_of_the_DB";
String user="username"; //the username that you use to login to the database
String pass="password"; //the password you use to login to the datatabase
 
            Class.forName("com.mysql.jdbc.Driver").newInstance();            conn=DriverManager.getConnection("jdbc:mysql://"+ip+"/"+db_name,user,pass);
        }
    }

Closing connection:

protected void closeConnection() throws Exception {
        if ((conn!=null)&&(!conn.isClosed()))
            conn.close();
    }

Use the above methods to open the conn and use it to run queries:

public boolean validatePassword(String user, String pass) throws Exception {
        this.openConnection();
        
        String query="select username, password from users where username='"+user+"' and password='"+pass+"'";
        Statement st=null;
        ResultSet rs=null;
        String u=null;
String p=null;
        
        try {
            st=conn.createStatement();
            rs=st.executeQuery(query);

                if (rs.next()) {
                    u=rs.getString(1);
p=rs.getString(2);
                }
                rs.close();
                rs=null;
                st.close();
                st=null;
this.closeConnection();
return ((u.equals(user))&&(p.equals(pass)));
        } catch (Exception e) {
            System.out.println(e.getMessage());
this.closeConnection();
        }
        return false;
    }
Alex Edwards commented: Very nice post! +2
peter_budo commented: Nice post. +9
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

The code will be the same. It doesn't matter for what you are going to use it. I will post the code soon, after I finish some other issues I have.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

to java addict:

i have tried your suggestion..unfortunately,it doesnt display the third array or array C that will display the product of the contents of arrays A and B...

The result in not an array, but the sum of the A*B
So I told you that you can omit the third array and instead of doing this:


C[i] = A[i]*B[i];
//..........
sum+=C[i];

You can do this:

sum+=A[i]*B[i];

That is the result you will get from ejosiah 's code. He doesn't use a third array.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

to java addict:

have you tried maing a running program for this???

What do you mean by that?

Also, I am not going to send the entire program like ejosiah did. You already have complete program as you posted on 2 Days Ago 12:52 3rd post. All you have to do is change where you calculate the result with my suggestion. Actually ejosiah told you the same algorithm (sum += a * b) but he wrote a new program version. Since you have the solution then use it to alter the code you have: 2 Days Ago 12:52 3rd post.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

I think there is something called: "instance of". I don't remember by heart how to use so might want to search it, but I do know that it works almost like this:

Rectangle r = new Rectangle();
if ( r instance of Rectangle ) {
}

But you'd better search it on the web to make sure.

Also you can try to do: r.getClass().toString() and then compare the String with the String Rectangle. Keep in mind that the above method also returns the package:

r.getClass().toString() returns packagename.Rectangle

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

After putting numbers in both tables and calculating the third table

Instead of this:

System.out.print("\t[A]\t[b]\t[C]\n");
for(int i=0; i<length; i++)
{
System.out.println("\t" + arrayA[i] + "\t" + arrayB[i] + "\t" + arrayC[i]);
}

You will need this:

int sum=0;
for(int i=0; i<length; i++)
{
sum = sum + arrayC[i];
}

Or without the third array:

int sum=0;
for(int i=0; i<length; i++)
{
sum = sum + arrayA[i]*arrayB[i];
}
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Use a for loop that takes the values of the arrays and do this:

sum = sum + a*b;

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

As you can see for each line, you have a start, then increase each element by 1 and when you reach 5, if you didn't insert 5 elements in the line start reducing.

5 4 3 2 1(start)

4 5(reached 5, will decrease until the line is filled) 4 3 2(start)

3 4 5(reached 5, will decrease until the line is filled) 4 3(start)

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

You say that the rate argument in any version of your computeCommission is measured in % .

Since in both cases you divide the input by 100 means that you assume if you
input 3 you mean 3% --> 0.03
input 3.0 you mean 3.0% --> 0.03
input 4.5 you mean 4.5% --> 0.045

So if you want the rate to be 0.45 (45/100 --> 45%) then the input should be:
computeCommission(double s, 45) or computeCommission(double s, 45.00)

So if you want the rate to be 0.06 (6/100 --> 6%) then the input should be:
computeCommission(double s, 6) or computeCommission(double s, 6.00)

So if you want the rate to be 0.053 (5.3/100 --> 5.3%) then the input should be:
computeCommission(double s, 5.3)

You say:

if i put int= .075 which would be 7.5%

If you want 7.5% (0.075) then you should input: computeCommission(double s, 7.5)

You get the error because int rate is an int variable and you cannot store non integer values. In int rate you must put only ints. If you do int rate=0.99999, the the rate will have value 0 in the end.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

What errors do you get? Does the program compile, run? Do you get the desired results?

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

I will have to take a better look on your code then for your last question:

my devices for calculating the number of characters, words and lines don't work as they should, or at least, as I thought they would. Any suggestions on that part?

Try to use files with one word and one line and see if it works.
Then files with one line and many words.

Try to test simple cases first and see how they behave.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Then create a method in the class that loops the two arrays and checks one by one the elements.

static boolean areEqual(int [] arr1, int [] arr2) {

if (arr1==arr2) return true; 
// if (arr1 != arr2) don't return false. Their elements might be the same

if (arr1.length != arr2.length) return false;
//No need to compare their elements if the arrays don't have the same length

/*
loop through the arrays (don't worry, they have the same length as checked above)
if one of the elements  of one array, 
is not equal with the other's array element then immediately return false 
if the loop finished and false was not returned then all the elements are equal, 
so return true at the end of the method 
*/
}

Use the above method when you want to compare the arrays

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

You can put the System.out.println() inside the while-loop:

while (more)
      {
        try
        {
            System.out.print("Please enter the file name: ");

            String input = console.next();
            FileReader reader = new FileReader(input);
            Scanner in = new Scanner(reader);
            counter.read(in);
            
        }
        catch (FileNotFoundException exception)
        {
            more = false;
            System.out.println("Characters: " + counter.getCharacterCount());
            System.out.println("Words: " + counter.getWordCount());
            System.out.println("Lines: " + counter.getLineCount());
        }       
      }

And then after the line: counter.read(in) , you should print the results. So when the while-loop repeats itself, you will be asked for a new file, and the results of the new file will be printed before the while tries to do another loop. And if you want to stop just enter a file that does not exist.

I don't think that you entered in an infinite loop. The program was just waiting for you to enter something, but since you didn't have any message before the console.next() , you didn't know that the program had stopped at that line and was waiting for your input.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

If you run by hand both for-loops, you will see that the x,y take value from 0 to 5.
They go: 0, 1, 2, 3, 4, 5. You correctly insert data in the arrays. When the index reaches value 5, then this statement is false:
( y=0; y<Arr2.length; y++ ), So the loop correctly stops:

Array[0] = 5
Array[1] = 5
Array[2] = 5
Array[3] = 5
Array[4] = 5
Then x or y becomes 5 and the loop stops

BUT then you do this:

if (Arr1[x]==Arr2[y])

. The x, y have value 5 and it tries to access the 5 element of the array. But the array can have as index only 0 to 4.

Don't '==' to compare arrays. Use this: Arr1.equals(Arr2). Or create another for-loop that compares each element with each other

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

I think:

MySubType mytype = null;
//instead of MySuperType mytype = null;

if (sub_type) {
     mytype = new MySubType ();
     mytype.setD(4);    
     mytype.setE(5);
} else {
     mytype = new MySuperType ();
}

mytype.setA(1);
mytype.setB(2);
mytype.setC(3);

MySuperType mytype = new MySubType ();
No because superType is not a subType. Super type does not have d, e variables.
Sub: has a,b,c,d,e so it does not "fit" in the Super which has a,b,c

MySubType mytype = new MySuperType ();
Yes because SubType is a SuperType. Sub type has a,b,c
MySuperType has a,b,c and it fits into the larger Sub

Try to compile and run both with sub_type true or false and see which one is correct.

Please correct me If I am mistaken because I don't have time to test it

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Sorry for the second post but here is the API for the charAt: String

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

You can for-loop the String using the charAt method and checking each time if the char taken is one of those: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.' . Also you should check if the '.' appears more than once

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Let's assume that you use Scanner to read input: Scanner.readLine() I think is the method and you store it into a String variable. There is a method that turns the String into an int:

String s = "10";
int i = Integer.parseInt(s);

The int i variable has the int value 10. If s is not an int number then the Integer.parseInt(s); will throw an Exception:

try {
 String s = "a";

 int i = Integer.parseInt(s); //this line will throw a NumberFormatException. It will also throw it if you use Integer.parseInt to turn into an int the String: "2.35" which is a float number

 System.out.println("The s is the int number: " + s); 

} catch (NumberFormatException nfe) {
 System.out.println("The s is not a number, s: " + s);
}

For more information:
Integer
Double
Float

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

IF you know C# then you will have little difficulty converting it to java on your own. It will not take you much time to read a few things about java. If you know C# you don't need to learn anything new, just understand a few things about how java works.
If you know C# and you didn't just find someone else's code and you want to convert it to java for your assignment.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

What errors and what code did you use to connect to the db? Is the applet displaying correctly?
Try to remove the code that connects to the database and see if the applet displays correctly. Have you tested separately in a main method if you connect and read from the database correctly?

PoovenM commented: You're good :) +2
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Instantiate the TimeListener target; in the ClockCanvas constructor before you use it.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster
public ClockCanvas(String c,String tz)
{
city = c;
calendar = new GregorianCalendar(TimeZone.getTimeZone(tz));
Timer t = new Timer(1000,this.target);
t.start();
setSize(125,125);
}

I believe that in the above code the target: this.target is null;

Your NullPointerException: target.timeElapsed(this); was because target was null. I have search from where it takes value and found the code that I present in the beginning of the post. The ClockCanvas(String c,String tz) is the constructor. Above that constructor you declare: TimeListener target; So when you call for example:

contentPane.add(new ClockCanvas("San Jose","GMT-8"));

the TimeListener target member of the ClockCanvas doesn't take value. So in this:

Timer t = new Timer(1000,this.target);

this.target is null. Then you call the start method and you get a NullPointerException.

Next Time try to put your code in a try-catch and do a printstackTrace(). That way you will be able to see not only where the exception was but also the path it followed before it is thrown. If you have done that you would have seen all the calls that took place and you would have spotted the place where the null target takes value (or doesn't)

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Read a HTML tutorial: This is what I prefer:
w3schools

And you are at the wrong forum. I think there is a forum for JSPs

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Even if you create your own Exception you will still need to implement some sort of validation in order to decide whether to throw the exception or not. So it up to you to decide, once you have made the validation, if it is necessary to throw an Exception or not.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

First of all you can have only one compareTo method, meaning that you can only have one rule for sorting. You cannot dynamically choose based on what you will sort. That is defined in the compareTo method. When you implement the method it will only sort based on that. If you want to sort using something else you will have to change the method.
The sort method of Collections will use a specific algorithm for sorting. As you know any sorting algorithm compares the elements it will sort with each other in order to see which is greater or lower in order to sort them. But how will the sort method of Collections determine which is greater or lower in order to sort them? It will use compareTo method and you will have to tell it when it compares two elements which one is greater or lower in order to do a swap or whatever the algorithm does.
So, when you have two objects, and someone (like Collections.sort()) asks you: Which one is greater?, what will you tell him? I will tell him for eg. that the first is greater because the variable height is greater (or lower, do whatever you want) than the other's objects.
So how will you compare these two BookingResponse objects. What will be the answer to the above question? If you want them to be sorted based on the Origin, then decide which object's Origin is greater, lower or equal than the …

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

I think I found it. Under your first post there is a link "Reply to Thread" with orange background and an arrow. Next to it, there should be what you are looking for. It is above the area where you can post a quick reply

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Somewhere in this page there has to be a link that says Solved

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Inside the compareTo method you will say how you want the objects to be compared.
Assume you have an Object with attributes name, height and weight.

If you want them to be sorted based on the height. write: (I don't remember the exact signature of compareTo so just pay attention to what is inside)

int compareTo(AnObject obj) {
 if (this.height>obj.height) return 1; //a positive number
 if (this.height<obj.height) return -1; //a negative number
 return 0; //if both heights are the same
}

Do the same if you want them to be sorted based on their weight.
Remember that equals is used for comparing if two objects have the same values so when the compareTo returns 0 doesn't necessary means that equals will return true. It may do, it do not.

About your case based on what you want them to be sorted? if it is based on Origin as you said, and if Origin is String then:

int compareTo(BookingResponse obj) {
   return Origin.compareTo(obj.Origin);
}

Or you can use your own criteria. Just remember to return positive, negative or 0 depending on how you want them to be compared

Ezzaral commented: Clear and helpful +6
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

One thing I forgot. The compareTo method will compare the objects in any way you like. Meaning that in your case you will only use the Origin in order to compare the objects. If it is a String use the compareTo method of the String class as your return statement.
And as you will read if you return 0, the equals method doesn't have to return true.

Meaning that you might want to sort two object based on the 'age' for example but the equals method will use the 'name' in order to determine if they are equal. That is for a hypothetical Person object

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

I believe that the Collections class has a sort method: Here is what you must do:

Your object that you put inside the ArrayList has to implement the Comparable interface. When you do that you will have to implement the compareTo method that compares this object with another object. This method returns a positive number if this object is greater, 0 if it is equal and negative if it is lower.
Check the API for the Comparable interface and the compareTo method.

Then use the sort method of the Collections class that is static and takes as argument your ArrayList.
Check the API for the classes: java.util.ArrayList , java.util.Collections, java.lang.Comparable
If you don't know the links for the API's let me know

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

char should have length 1. Always 1.
This is correct char c=' '; or char c='2'; Not this: char c=''; or this char c='12';
So I believe that the compiler could convert the '\21' to its equivalent character but not '\29' because there isn't any. Is like writing: char c='\n'. n is a special character for newline. But char c='/n' is not correct.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

break statement inside the loop doesn't make it an infinite loop. (that's my opinion of course) Others might have better suggestions

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

There is an error because argument1 is an Object and can't call the xyz method. Remember
the class abc may be an object(meaning you can use it as an argument at the method)
but an object is NOT an abc class(meaning that the argument Object does not have a method named xyz).
That's because you could have called that method with any other argument (an other object but not an abc class) and then your method would throw an Exception.
If you want it to work try:

methodname (Object argument1)   //argument1 is instance of class 'abc'
{
       (abc)argument1.xyz();  //xyz is method in class abc,
}

It will again throw an Exception if you use as input an object that is not abc

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

First create a class Ferry with the necessary attributes and method for adding passengers. Use the assignment's specifications in order to find out what methods you should have and they should do.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

I think, masijade, that he wants to call this method:whateverMethod(Object obj) with any kind of object and for the method to do what is necessary every time dynamically. Meaning that I don't think that he intends to check what type of class he is passing in order to do casting.
Perhaps if he wants to save the object he is passing, he should consider serializing/desirializing

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

From what I understood you have declared the array to contain objects, but you insert Strings. Why don't you create a class with two attributes: name and description and insert that in the array. So when you get the object from the array you will have access to each of these values separately with get methods(getName(), getDescription()).
Now, about your problem:
If you have declared the array to be an array of objects then when you get values of the array you get an object. ex:

Object [] array=new Object[5];
array[0]="Name:Description"

the array contains objects, you insert String which is an Object.String is an Object
BUT when you do this:

String s=array[0];

it is wrong because the array returns an object, not a String:Object is NOT a String
and the method substring applys only for Strings not objects, meaning that you should use casting:

String s=(String)array[0];

If the object that is inside the array ia a String then the casting will work, otherwise it will throw an Exception

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

You must add the Panel to this JFrame

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Piers said:

Use Split. Go to the java API and it will tell you how to use it.

split is a method of String class

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

I am not going to do your homework for you. I gave the code for reading lines from a file. Each line is stored in the String: String s=bReader.readLine();. What you do with the string is your job. Is not that difficult; use StringTokenizer, or split(), and then make the necessary checks.
I don't know what the assignments says, but you could create a class with 3 attributes. Every time you read a line, create a new object with values, the values you get from the line, and store that object in an ArrayList, or Vector.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster
FileReader reader=new FileReader(new File("filename"));
BufferedReader bReader =new BufferedReader(reader);

String s=bReader.readLine();

The API says that readLine() returns null if the file has ended, so you can do something like this:

boolean b=true;
while(b) {
  String s=bReader.readLine();
  if (s==null) {
    break;  //file has ended
  }
}
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Where do you get your error at the following?
And why do you have size as an argument since you are calculating it in the method. It won't matter what value it will have when you call the method since it will take a new value; the size of the array.

well i have this print method but when ever i try 2 use it it give me an error illegal start of expression
so any idea

private static void displayResults(String[] rooms, int size)
{
int size=rooms.length;
JTextArea textArea = new JTextArea();
textArea.setEditable(false);

// Print Array output text area:
for ( int i = 0; i < size; i++ )
textArea.append(rooms[i]+"\n");

// Display the Array via a message dialog box:
JOptionPane.showMessageDialog(null, textArea);

}
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Use the code tags without the ' in the tag:

//code

Don't put the ' in the above tags

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

if (str1==str2) returns false correctly because they are two different objects.
if ( str1.equals(str2) ) will return true, because it compares their values.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Have you added the changes to your code? If you have what errors do you get know and what is your problem? Perhaps you should post you newly updated code and tell us in what you are having difficulties

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

I would suggest first to get the int value of the method and then check it if it is -1:

int i = name.indexOf(",");
if (i!=-1) 
  FirstName = name.substring(0,i);
piers commented: thnx you have helped me kill 2 birds with 1 stone +1
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

The getters return null because the values first,lastName are null. If you see the constructor they never get values.
The constructor:

public Name( String name)
{
name = FirstName + LastName;
}

is wrong. The argument's value must be inserted somwhere:

public Name( String n)
{
  name = n;
}

The first constructor and the while are also wrong.
What you have inside the while is wrong because you are changing the value of name. You don't want that, that's the value that you are checking and have at the for loop. If you change that, the for-loop is going to get messed up.
Read the String API and you will find 2 or 3 useful methods to use without using for or while loops.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

I would suggest copying the query in an sql editor and try to run it by replacing only the '?' with values.