javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

can anyone please make changes and comment my code if u are good at it. that will be really a great help. Thanks again

if u are good at it

Yes, we are good at it

What does this suppose to mean? Have you any idea what you are asking. It's not enough that you cheated at your assignment, you have the nerve to tell us that you cheated and still ask for help. Help not for the code but how to help you cheat better!!

can anyone please make changes and comment my code

It is not your code.

VernonDozier commented: Good points. +24
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

the values to array "selElts" are returned from a javascript function

The selElts you define in javascript is not the java array. They are not the same. What you have written doesn't work. You can not call javascript method to give values to java variables.


If you want to send something from one page to the other, you either submit the form and get the values with request.getParameter("")
or set the request Attributes and redirect.

If this doesn't make sense, study harder and learn about servlets and jsp

kvprajapati commented: Good suggeston +13
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

The import DBManager cannot be resolved

You need to import the class:

<%@ page import="package.DBManager"%>
peter_budo commented: Good answer, but you should let him sweat little +22
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Do not even look at this code , just write java code to calculate total sale price from user inputs .

I get it now.
I was sent a PM from chingkoysilog (the OP) asking to give him the solution of an assignment that involved salespersons and calculating some total values per products and salespersons.

He probably found the solution from the internet in C++ and now wants someone to convert it in java.

If chingkoysilog disagrees then please correct me, by posting your code and explaining what is your problem so we can help you.

ithelp commented: ok. +12
iamthwee commented: yeah he got the code from daniweb +22
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

I would suggest that you stop working on this servlet thing and start learning some basic java because this error is very basic and usually done by beginners.

You declare the Map in one method locally and you try to access it from another method.
Declare it globally or declare another Map in "doGet" depending on what you want.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Then why don't you look at this link:
JSP database connectivity according to Model View Controller (MVC) Model 2

It is at the top of the Jsp forum.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

First of all I find it surprising that you wrote this code and still couldn't find the answer.
I mean was it so difficult to add this to your code?

if (lineNo==5134)
{
  line = br.readLine();
} else if (lineNo==5100)
{
  line = br.readLine();
} else if (lineNo==5200)
{
  line = br.readLine();
}
..
..
..
 else {
  br.readLine();
}

Of course you code prints only one line because you have only ONE variable "line". If you want to print all of them either add a
"System.out.println" at the place that you read them:

if (lineNo==5134)
{
  line = br.readLine();
  System.out.println(line);
} else if (lineNo==5100)
{
  line = br.readLine();
  System.out.println(line);
}

Or declare an array that will store the line that you want:

String [] lines = new String[N];
int i=0;
.....
if (lineNo==5134)
{
  line = br.readLine();

  lines[i] = line; 
  i++;
} else if (lineNo==5100)
{
  line = br.readLine(); 

  lines[i] = line; 
  i++;
}

But that wouldn't be quite correct.I have noticed the way you read the file:
>> for(lineNo=1;lineNo<10700;lineNo++)
It is wrong. In general you wouldn't know how many lines the file has. So instead of the for loop use this:

FileReader fr = new FileReader("C:\\IMS.txt");
BufferedReader br = new BufferedReader(fr);
int lineNo = 0;

String line = br.readLine(); 
lineNo++;

while (line!=null)
{
  // do whatever you want with the line or the line number
System.out.println("Line Number: "+lineNo+", Line: "+line);

  line = br.readLine();
  lineNo++;
}

Whenever you read a new …

BestJewSinceJC commented: OP didn't mark as solved, although it was solved. +8
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Classes begin with capital. Methods with lower.

StringConcatenate stringConcatenate1 = new StringConcatenate(); 
stringConcatenate1.stringConcat();

You create an object/instance of type StringConcatenate. And you call the method stringConcat() of the instance stringConcatenate1.

Most of the time different instances have different results when they call the same method:

StringConcatenate string1 = new StringConcatenate("aaa"); 
StringConcatenate string2 = new StringConcatenate("bbb");

string1.stringConcat();  
string2.stringConcat();

That is why we create different instances of the same class.

Also this would only be correct if the method was declared "static"

StringConcatenate.stringConcat();

If the method is static you don't need to create an instance to call it

majestic0110 commented: Excellent response, thank you! +4
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

I don't know if this the case, but you MUST first call: rs.next() to get the row from the ResultSet.
Meaning that when you do: String Instructor = rst.getString("Instructor"); you probably get an exception, go inside catch, and nothing is displayed:
Also about this:

if (Instructor == null) 
    Sorry, no match for that user in our database. Please try again.

If there is no match the rs.next() will return false. So you need an if statement checking that. If it is false, THEN there is no match. If there is no match then the rs.next() will be false not the Instructor null. If you manage to call rs.next() and the rst.getString("Instructor") then there was a row returned so there are values to retrieve.
When Instructor is null doesn't mean that there were no rows. It means that you got a row from the database and the table column with name "Instructor" doesn't have a value. Of course if "Instructor" is Primary Key that would be impossible but I am talking in general.

So I suggest, first put some message inside the catch that are printed at the page:

catch (ClassNotFoundException e) {
            System.err.println("Could not load database Driver!");
%> <%= e.getMessage()%> <%
        } catch (SQLException e) {
            System.err.println("Could not connect to to the database!");
%> <%= e.getMessage()%> <%
        }

And then and MOST IMPORTANT do whatever you want to do from the beginning but this time follow the tutorial at the top of the JSP forum with …

CodeBoy101 commented: This guy is one of the best reasons to come to Daniweb!! +2
VernonDozier commented: Good advice. +16
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

But even if you can use it for declaring methods, you shouldn't. It is better to declare methods and variables with English characters and English descriptions since it may be read by others.

No you shouldn't use unicode for declaring methods and variables.
You use unicode for unsupported characters. If your keyboard has the 'a' then use it for the name of your method. What's the point to use unicode then

puneetkay commented: Thanks for helping! +2
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

From what I understood, first you delete and then you insert, when you want to do an Update.

Well you can try and run an Update query. When you "SELECT" data from the database you use a userID as you say in your example. Probably you use it at your "WHERE" clause at the query to get the data (UNIMP and IMP).
You can have ONE update query setting the values of the UNIMP and IMP data taken from the TextFields.

Or if for some reason that cannot be done, you can use "commit", "rollback".
First set the autoCommit of the connection to false.
Run your queries.
If both where executed: commit and set back the connection's autoCommit to true
Else if there was an exception do a rollback inside the "catch (Exception e) " and again set back the connection's autoCommit to true

All the above methods are available from the Connection class. Check its API for more info

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Do you have somewhere another class named Random?

freelancelote commented: thanks a bunch +1
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

dis shite shzucks

You will find no servants here that are obligated to answer to your questions. If you didn't get a reply it was probably because people didn't know the answer or they were busy with their own (personal or not) problems.
No one here has anything against you so not to answer to your post. Don't act like we didn't answer because we had some grunge. I don't know you. If I had something useful to say 3 months ago, I would have said it.
No one offended you. No one guaranteed that we will immediately solve all your problems

VernonDozier commented: Well said! +16
Ezzaral commented: Agreed. +23
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

The answer is simple English grammar:

A method throws an Exception:

public void method(int i) throws Exception {

}

The method throws an Exception when you call it


But you throw an Exception:

if (i<0) throw new Exception();

If 'i' is negative you will throw an Exception.

And if you put it together:

public void method(int i) throws Exception {
      if (i<0) throw new Exception();
}
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster
Ezzaral commented: Good suggestion +21
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

First of all what type of argument does ps.setDate() have and what type are the to_date, from_date at your database?

Also if you need to convert a String to a Date try this:

String sDate = 01/04/2009;  // 1st of April
String format = "dd/MM/yyyy"

SimpleDateFormat sdf = new SimpleDateFormat(format);
sdf.setLenient(false);

Date date = sdf.parse(sDate);

Check the API for more: SimpleDateFormat

peter_budo commented: Simple and effective solution +18
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Well this is what I got with mixed numbers:

[1, 2, 3, 4]
[4, 3, 2, 1]
Enter the value you want to search for
4
The value you searched for is at index -5

It should have returned '3'.

After searching the API for collections
found that the method you are using :
int binarySearch(List<? extends Comparable<? super T>> list, T key)
requires a list that implements the "comparable" interface. so when I tried this I got an error: int where = Collections.binarySearch(Arrays.asList(a), searchValue); Because Arrays.asList(a) returns an Object list that doesn't implement the Comparable.
But there is another method you could use if it is not a limitation:
int binarySearch(List<? extends T> list,
T key,
Comparator<? super T> c)

Instead of implementing the Comparator, the API says that if you enter null: A null value indicates that the elements' natural ordering should be used. So it will use the comparator of the Integer class.
so try this:

Object[] a = mylist.toArray();
		Arrays.sort(a);
		System.out.println(Arrays.asList(a));
		//not working because mylist is not sorted in ascending order
		//must make sorted list the parameter for the Collections.binarySearch
		System.out.println(mylist);
		System.out.println("Enter the value you want to search for");
		int searchValue = scan.nextInt();


		//int where = Collections.binarySearch(mylist, searchValue);

		int where = Collections.binarySearch(Arrays.asList(a), searchValue, null);


		System.out.println("The value you searched for is at index " + where);
Grn Xtrm commented: Big help. Thanks. +1
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Try this one....
Regards
.................

Congratualtions,
The oldest thread reviving I have ever seen. Not to mention all the forum rules that you've just broken. (We do not give away free homework and we use code tags)
Last post by server_crash was May 8th, 2005 14:16.
What were you thinking? :)

Salem commented: Just another noob who's discovered their first programming "fact" and is rushing madly around looking for someone to tell like it's the most important thing in the world. +29
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

I will pay $5!

I know that there is an economic crisis all over the world but thank God, we are not that desperate. :icon_cheesygrin:
In my country, with the taxes and the insurance, I would have only $2.9 left!!! :'(

Salem commented: OP pays you $5, flunks and works at burgerworld. You support the OP again by spending $2.9 at burgerworld. +29
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

I will pay the first person to finish this task via paypal!!!
I will pay $5!

Only $5 !! You have to be insane.

Firstly, the amount in insulting. In this forum there are many professional programmers that get paid much much more. Why should they bother to fix your problem? Not to mention that even if someone else would do this the amount is nothing near to what is necessary to tempt someone to do this. If you think this worths only $5 do it yourself

AND SECOND and most important. This is a forum for people to learn. We do not give away free code. And when I say "free", I don't mean code that people pay with money, but with effort.
Those who want help have showed with their questions and their efforts that they deserve it. And you will see that we have given code to many people, which was very close to the actual solution of their assignment, only because their attempts were genuine and they were as close as they could get.
This despicable offer of money is insulating to ALL the members of this forum that use their spare time to teach others and offer solutions free of charge because they want to, not because they are paid.
What you suggested can only be interpreted as a miserable attempt to bribe the members of this forum to betray their ideals and the other members of this forum.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

The first error is easy. You cannot compare String using this: "<". For Strings you need to use this function:

if (  txt_pay.getItem().compareTo(txt_amount.getItem())<0  )
{
   jOptionPane1.showMessageDialog(this, "please enter the right amount");
}

And when you do this:

if (txt_pay.getItem().isEmpty())

The method isEmpty() needs to return a boolean value.

Also in java the 'null' value is this null

if (txt_pay.getItem() == null) // 2 '=' symbols when comparing

Also use this '==' when comparing a String with a null value like above, but if you want to compare 2 Strings that have value use this:

if ( !txt_pay.getText().equals("")  )

Also this converts a String into a numer

String s1  = "22.22";
double d = Double.parseDouble(s1);

String s2  = "13";
int i = Integer.parseInt(s2);
jam7cacci commented: fantastic! he's a great help +3
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Of course, now I see it. It is very simple. The executeQuery is supposed to return a ResultSet. You use that method when you are querying the database (select * from ...) and you expect to get back some rows.

But the query you have is an INSERT query. You are asking for the database to return you a ResultSet: rs1=stmt.executeQuery("insert into userinformation(username,password,dateofreg) values ('"+name+"','"+password+"','"+dateofreg+"')"); But the INSERT query doesn't return anything, it is simply inserting.

So use this method:

int executeUpdate(String sql)

Executes the given SQL statement, which may be an INSERT, UPDATE, or DELETE statement or an SQL statement that returns nothing, such as an SQL DDL statement.

The int that returns is the number of rows affected. In your case will return the number of rows inserted (1)

Also next time you should check the API of the classes you are using:
Statement

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

You need to count how many elements are inserted and when you reach 10 exit.

If I understood correctly you will need this:

int count = 0;

do {
System.out.print("Enter 1 for F to C, 2 for C to F, and 3 to quit");
choice = input.nextInt();
if (choice == 1) {
count++;
tempC();
} else if (choice == 2) {
count++;
tempF();
} else if (choice == 3) {
exit();
} else {
System.out.println("Invalid selection");
}
if (count==10) {
  choice = 3;
}
} while (choice != 3);
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

First of all you open a bracket where it is not needed:

Double payRate = input.nextDouble();
System.out.println();{

//Input the  name of the employee
      System.out.printf( "Please enter the employee's  name ('stop' to quit): " );
       employeeName = input.nextLine();
      if (employeeName.equalsIgnoreCase( "stop" ) ) {
         break;}
  
         // prompt and input hours worked
       System.out.println("Please enter hours worked: " );
     Double hoursWorked = input.nextDouble();
      // read value for hours worked
      if(hoursWorked <=0.0){
          System.out.println("Hours worked cannot be negative/zero.");
      }
      else{
      // prompt and input pay rate
      System.out.println( "Please enter pay rate: " );
     Double payRate = input.nextDouble();
      System.out.println();
      if (payRate <=0.0){
          System.out.println("Hourly wage cannot be negative/ zero.");
      } 
      else{
     double weeklyPay = hoursWorked * payRate;
                PrintStream printf = System.out.printf("Weekly pay is $%.2f", weeklyPay);
}
}

I have changed the variables because you do this:

Double hoursWorked = input.nextDouble()
// read value for hours worked
if(hoursWorkedInWeek <=0.0) {


Also you get the error because you ask from the user to enter a number:

System.out.println("Please enter hours worked: " );
Double hoursWorked = input.nextDouble()

And you enter: 'stop'

stephen84s commented: To go this far with him, you really need should be given a much bigger positive rep. +5
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Who is stopping you from submitting it?

masijade commented: A great starting point. +11
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

From what I understood I presume that each line in the file will have many values (probably comma separated) that need to be put in each row of a 2D array.

If this is the case then when you read the line use the split method of the String class:

String s = "a,b,c,d";
String [] array = a.split(",");

Then the array will have elements:
array[0] = a
array[1] = b
array[2] = c
array[3] = d

Afterward you can take these values and put them wherever you want

puneetkay commented: Thanks for telling abt this method! :D +2
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

I don't want to sound ignorant, or pretend that I know everything, but does this code make any sense to you all?
Because if the purpose of the code is reading a specific file then I don't think this is the right way.

What exactly are you trying to accomplish?
What is it that it doesn't work?
What do you get and what do you expect?

jasimp commented: You mean you don't know everything ;) +9
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Ok I have managed to solve this one too:

I was using this:

<s:iterator value="listOfObjects">
  <s:property="code">
  ................
  <s:radio name="selectedCode" list="listOfObjects"  />
</s:iterator>

The above created a list of radios in each line:

Instead this was needed:

<s:iterator value="listOfObjects">
  <s:property="code">
  ................
  <s:radio name="selectedCode" list="{code}"  />
</s:iterator>

With the above I declare ONE sinlge radio, so as the iterator progresses each line has 1 radio. As for the value of the radio I took this example: http://struts.apache.org/2.x/docs/how-do-i-render-a-single-radio-button.html

peter_budo commented: Nicely done +12
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Move the code that reads the input in the while loop

stultuske commented: looks like you've got a lot of patience +3
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Don't worry everybody does that mistake. And I am tired of replying to it.

Just use the equals method.

When you use '==' to compare String (remember Strings are Objects) you compare to see if they are the SAME objects. They are not, but they have the same value:

if (Input1.equals("P")) {
 .....
}
String s1="a";
String s2="a"; //2 Different objects.

(s1==s2) //false
(s1.equals(s2)) //true

BUT

String s1 = "a";
String s2 = s1; //they are the same

(s1==s2) //true
(s1.equals(s2)) //true

Also you will need to have all of your IFs as 'else if':

if () {

} else if () {

} else if () {

} .... {

} else {
System.out.println("");
System.out.println("Error - Input not recognised!");
System.out.println("");
}
Laidler commented: the .equals method was very usefull in my studies +1
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

kindly please help to solve my problem???
create a program that the user allow to input a 5 integers, that looking the lowest value?

It would be useful to read a Thread before posting to it. Perhaps your question has already been answered.

jasimp commented: Good point. +9
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Two for-loops

stultuske commented: why make it harder if it indeed is this easy? +3
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

If you have studied from day one of the class and practice with simple programs you could do it.
Plus you attitude was not the best encountered here. Your tone was demanding, you just posted only the code with no explanations whatsoever as if it is our job to do other people's homework and why should we waste our time to complete this?

VernonDozier commented: Well said. +8
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Well for starters it always helps when debugging to add a ex.printStackTrace() in the catch:

System.out.print ("Caught a null pointer exception - ");
            System.out.println (ex.toString());   
            ex.printStackTrace();

After doing so, I noticed that none of your aruments is null. This is what I got:

java.lang.NullPointerException
at com.sun.imageio.plugins.common.PaletteBuilder.findPaletteEntry(PaletteBuilder.java:310)
at com.sun.imageio.plugins.common.PaletteBuilder.getIndexColorModel(PaletteBuilder.java:296)
at com.sun.imageio.plugins.common.PaletteBuilder.getIndexedImage(PaletteBuilder.java:145)
at com.sun.imageio.plugins.common.PaletteBuilder.createIndexedImage(PaletteBuilder.java:77)
at com.sun.imageio.plugins.gif.GIFImageWriter.write(GIFImageWriter.java:564)
at com.sun.imageio.plugins.gif.GIFImageWriter.write(GIFImageWriter.java:492)
at javax.imageio.ImageWriter.write(ImageWriter.java:598)
at javax.imageio.ImageIO.write(ImageIO.java:1479)
at javax.imageio.ImageIO.write(ImageIO.java:1521)

at ColorForms.TopPanel.SaveImageToFile(TopPanel.java:87)
at ColorForms.TopPanel.actionPerformed(TopPanel.java:46)

at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6041)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3265)
at java.awt.Component.processEvent(Component.java:5806)
at java.awt.Container.processEvent(Container.java:2058)
at java.awt.Component.dispatchEventImpl(Component.java:4413)
at java.awt.Container.dispatchEventImpl(Container.java:2116)
at java.awt.Component.dispatchEvent(Component.java:4243)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3986)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)
at java.awt.Container.dispatchEventImpl(Container.java:2102)
at java.awt.Window.dispatchEventImpl(Window.java:2440)
at java.awt.Component.dispatchEvent(Component.java:4243)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)

I have never used these classes before so I am not sure how they need to be instantiated. I believe that maybe when the java methods are called
(from the stack trace:
at javax.imageio.ImageWriter.write(ImageWriter.java:598)
at javax.imageio.ImageIO.write(ImageIO.java:1479)
at javax.imageio.ImageIO.write(ImageIO.java:1521)
)
something that was not supposed to be is null when they use your arguments. I cannot say much so you would better wait for someone better to see this and figure it out

Sorry

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

You can view a .class file like any other file: By opening it. Use whatever program you want to open it. But don't expect to see anything. Here is a sample of what a .class file looks like when I used PSPad:

CAFE BABE 0000 0031 0112 0A00 4E00 B409
002C 00B5 0900 2C00 B609 002C 00B7 0900
2C00 B809 002C 00B9 0900 2C00 BA09 002C
00BB 0900 2C00 BC09 002C 00BD 0A00 2C00
BE0A 002C 00BF 0A00 2C00 C00A 002C 00C1
0A00 2C00 C20A 002C 00C3 0A00 2C00 C40A
002C 00C5 0A00 2C00 C60A 002C 00C7 0700
C808 00C9 0A00 1500 CA08 00CB 0800 CC08
00CD 0800 CE0A 0027 00CF 0800 D00A 0027

As you can see it is binary code. Actually what you see is hex code (0,1,2,3,4,5,6,7,8,9,A,B, C,D,E,F) because this is how PSPad displays it, but in reality it is binary

Alex Edwards commented: I think he meant reverse-engineering, but that does answer the question! =) +4
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

PoliceOfficer class: Simulates a police officer
Responsibilities:
- To know the police officer's name and badge number
- To examine a parked car object and a ParkingMeter object and determine whether the car's time has expired.
- To issue a parking ticket (generate a parkingTicket object) if the car's time has expired.

That means that the PoliceOfficer class should have 2 more attributes:
parked car object and ParkingMeter object :
ParkedCar,
ParkingMeter

In your main you did these calculations:

difference = utimeParked - utimePurchased;
        if (difference < 0)

The utimeParked is part of the ParkedCar that the PoliceOfficer will have
The utimePurchased is part of the ParkingMeter that the PoliceOfficer will have

So write a method in the PoliceOfficer class that uses the above values taken from the objects ParkedCar, ParkingMeter that PoliceOfficer has.

PoliceOfficer {
  ParkedCar car;
  ParkingMeter meter;
  
  ....
  ....

  public ParkingTicket issueTicket() {
   //in here you will do the calculations
  //and return a ParkingTicket object
     difference = car.getMinutesParked() - meter.getMinutesPurchased();
   // do the calculations
  instantiate a ParkingTicket object and return it.
  }
}

I order for the issueTicket() method to work, the ParkingTicket will have to have these attributes:
ParkedCar,
PoliceOfficer,
AND:
amount of money to be paid.

You will not create ParkingTicket in main. You will get it when you call the issueTicket() and print what is recquired

Ezzaral commented: Helpful explanations in this thread. +12
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

If my sleepy mind does play tricks on me, you should do it as

(File)vector.elementAt(i).getAbsolutePath()

I think, although it needs to be checked that you should do this: ((File)vector.elementAt(i)).getAbsolutePath() Just a suggestion, I don't know if it will work, just try it, because resizing the array is bad idea.
Every time you change the vector you will have to create a new array AND store again the data, so try first the above before using the array solution

PoovenM commented: I totally agree :) +3
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Java is case sensitive. When you declare an instance like this:
Circle radius = new Circle(),
this would be wrong: Area = Radius.getArea().
This is correct: Area = radius.getArea()


Also you call a method:
Circle.setRadius(number) and that method doesn't exist. On top of that if it did exist you should declare it non static and call it: radius.setRadius(number)


You declare a constructor: public double Circle(double Rad) . Classes may have the default constructor so if you declare none you can use the:
Circle radius = new Circle() as you do in the code, bit since you declare a constructor you must use only that: public double Circle(double Rad)
or have 2 constructors


And lastly the constructor shouldn't return anything. This is wrong:

public double Circle(double Rad)
	{
		Radius = number;
		return Radius;
	}

Remove the return

peter_budo commented: This is for faste answer +10
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

I assume that the other program (GUI) has a list of classes. Do you know the elements of those classes as well as their methods. If the main GUI page has a constructor you call it with the appropriate data that you get from your program.
If the elements of the GUI are public you can 'set' their values, after you have called the constructor of the program in your main:

In general how you set values:

JTextField field = new JTextField();
field.setText("New Text");

In your main:

OtherProgramGUI gui = new OtherProgramGUI();
gui.field.setText("New Text");

gui.setVisible(true);

If all of the elements and the methods are private then you have a problem

PoovenM commented: Thank you for the awesome suggestion :) +3
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster
int i=0;
switch (i) 
{
  case 1:
      System.out.println("Value 1");
      break;
case 2:
      System.out.println("Value 2");
	break;
}

The code checks 'i''s value. When it finds a case that has that value, it executes what is under it.
So the above code will print: "Value 1". Then break will be executed and it leave the switch. If you ommit break, then it will go to print the next 'case'. It will not make a check at each case:

int i=0;
switch (i) 
{
  case 1:
      System.out.println("Value 1");
case 2:
      System.out.println("Value 2");
	break;
}

The above will print:
"Value 1"
"Value 2"
And then break. If you add default, it will be executed if no case is found with the number at the switch

int i=3;
switch (i) 
{
  case 1:
      System.out.println("Value 1");
case 2:
      System.out.println("Value 2");
	break;
default:
      System.out.println("Default");
}

Will print: "Default"
Again with this all of them will be printed, since the break is missing:

int i=1;
switch (i) 
{
  case 1:
      System.out.println("Value 1");
case 2:
      System.out.println("Value 2");
default:
      System.out.println("Default");
}

"Value 1"
"Value 2"
"Default"

Now you don't need brackets at the switch, case. It will execute anything that is below it until it finds break

int i=1;
switch (i) 
{
  case 1:
      System.out.println("Value 1");
//command 1
//command 2
//.......
      break;
case 2:
      System.out.println("Value 2");
default:
      System.out.println("Default");
}

Meaning that you can add anything you want at "command 1" even a second switch/case

peter_budo commented: Been fooled by silly request, but provide great work +10
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

If you don't know java why are you starting with gui when you don't know even the basics of the language?
Start by writing simple console programs and learn how to use classes, extending them . . .

stephen84s commented: Exactly +3
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

No you haven't tried what I have suggested. See the code for reading from the file, using BufferedReader and readLine()

Alex Edwards commented: Incredibly patient! +4
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

When will you ever say yes, or turn off your email blocking???

When will the madness stop???

=P

Madness?

This is SPARTA.


PS: And I am from Greece

peter_budo commented: You don't mess with the Zohan +10
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

The
int numberValue = Integer.parseInt(number) ;
does not throw a IOException. You are right to use it in the catch since readLine() does throw the IOException, but the parseInt() throws a NumberFormatException:

/**
 * @(#)GetUserInput.java
 *
 *
 * @author 
 * @version 1.00 2008/8/2
 */
import java.io.*;

public class GetUserInput 
{
         private static BufferedReader stdin = new BufferedReader( new InputStreamReader( System.in ) );

        
    
    
    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException
    {

     
            System.out.print( "Type some data for the program: " );


            // Read a line of text from the user.
            String input = stdin.readLine();
		


            // Display the input back to the user.
            System.out.println( "input = " + input );
            
            System.out.print( "Type a number for the program: " );

	
            // Read a line of text from the user.
            // then convert it to int but print error message if it goes wrong
             try
	    {
		String number = stdin.readLine();
	    int numberValue = Integer.parseInt(number);	    
            
            // Display the input back to the user.
            System.out.println( "Number Inputted = " + numberValue );
	
	    }
            // i want it to print the error message if if cant convert the string to an int
		catch ( IOException e )
	   {
	System.out.println(e);
      		System.out.println("Error while reading input: " + e.getMessage());
           }
catch ( NumberFormatException e )
	   {
	System.out.println(e);
      		System.out.println("Given input not a number: "+e.getMessage());
           }
   
    }
}
Alex Edwards commented: Helpful individual +3
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Since they are interfaces, you can implement more than 1:

public class MyFrame extends JFrame implements ActionListener, ItemListener {

}

Don't forget to add the methods that these interfaces have. Also to add the "listeners" to the components you are interested (buttons)

Alex Edwards commented: Credit is given where credit is due +3
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

Could someone help java code to read number of lines, words and characrters in paragragh .

You can count how may times the \n appears in the paragraph for lines.
For characters the total length of the paragraph String minus the characters: " ", " ", " ", ...
For words user String.split(" "); and count the length of the array minus the elements where you might an empty String with more than one length.

Or you can use regular expressions.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Do you know WHY you increase the index in the addAdvice method? You increase it because when you add a new advice you don't want it to be placed at the same place as a previous inserted advice. Now look at the constructor and the addAdvice

public Oracle ()
{
advice = new String[5];
index = 0;

advice[0] = "It's as simple as this";
advice[1] = "Search engines like google are great!";
}

public void addAdvice (String entry)
    {
           
       if (index < advice.length) 
       {
           advice[index] = entry;
           index++;
       }
       return;
                   
    }

If you call the constructor and then the add method, the index in the add method will have value 0. So the advice passed as argument in the add method will be placed at the '0' place of the array which will overwtite the "It's as simple as this" of the constructor.

Since you "add" two "advices" in the constructor, you should also increase the index twice as well

Ezzaral commented: helpful point +9
sktr4life commented: thanks for the explanation (arrays) +1
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

First:
I don't know why you need this and what you are trying to print:

String[][] strings = (String[][]) lines.toArray(new String[lines.size()][]);
System.out.println("strings are "+strings[0][0]);
System.out.println("Lines="+strings.length);

Do you what split does? If you knew, then when you do: fields[0] you print the first value of each line. Example

String line="a b c d";
String [] tokens=line.split(" ");

tokens[0] has value: a
tokens[1] has value: b
tokens[2] has value: c
tokens[3] has value: d

From you pm:

could u just write a simple code for example to read from
asdf xcvf ghjk esks
0.21 3.22 1.23 2.45
43.3 3.33 2.21 11.3
2.22 2.44 2.55 3.67

and to get values under ghjk ie 1.23, 2.21, 2.55

Then do

String[] fields = line.split(" ");
System.out.println("fields size is "+fields.length);
System.out.println("fields value is "+fields[2]);
lines.add(fields);

Inside the lines ArrayList you will have the 3rd column of each line.

If you want the y column of the x line as you state in one of your posts then, inside the for loop count the lines with an int variable. ( countLines++; )
When you reach the desired line take the desired column:

//y column
//x line

int count=0;
for(String line = br.readLine();line != null;line = br.readLine()) {
 count++;
 if (count==x) {
  String[] fields = line.split(" ");
  System.out.println("fields size is "+fields.length); 
  System.out.println("fields value is "+fields[y-1]);
 }
}

In the last for-loop the if will be executed only ONCE for the line …

VernonDozier commented: Good post. +3