javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Try to add some System.out.println in the readFile method and see what happens. Also you need to declare the list as a private member of the class like filePath. With your way, you create it in the method readFile and then after it executes, you have lost it, you cannot access it

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Check if the connection is created to the database

Connection con;
Statement stmt=con.createStatement();
ResultSet rs=null;

String ss=("SELECT VIDEOID, VIDEONAME, DIRECTOR FROM VIDEOS");
rs=stmt.executeQuery(ss); 
while(rs.next())
{
//code goes here
}

That is not what TIM_M_91 has asked.


@TIM_M_91:
It is odd that you haven't found the correct syntax because all you needed is some basic tutorials about sql: http://w3schools.com/sql/default.asp
Any way, you can add this to your query:

SELECT VIDEOID, VIDEONAME, DIRECTOR 
FROM VIDEOS
WHERE VIDEOID=[I]something[/I] AND VIDEONAME=[I]somethingelse[/I] ...

Instead of AND you can use OR

The columns that you use as filters don't need to be at the select. This query is valid for example:

SELECT VIDEONAME
FROM VIDEOS
WHERE VIDEOID=[I]something[/I]

If you want to put it in java, using the Statement interface (as in your code) you can try this:

String videoId = "some_value";

String ss="SELECT VIDEOID, VIDEONAME, DIRECTOR FROM VIDEOS";
ss += " WHERE VIDEOID='"+videoId+"'";

System.out.println("Executing query:"+ss);

rs=stmt.executeQuery(ss);

What's out for the single quotes ' . The value of the ss is the query executed so print it and see what you have.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

you can catch array index out of bound exception.

Never use try-catch for ArrayIndexOutOfBoundsException. You already know at runtime the size or length of what you are trying to use. So always check that.

long89:
So when looping, it is good to do this instead of what you have:

for (int i=0;i<people.length;i++) {
 // use people[i]
}
stultuske commented: agreed. avoiding an indexoutofboundsexception is way better than handling it. +14
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

You can load the servlet directly. Instead of writing at the url:
http://localhost:port/index.jsp

you can write:
http://localhost:port/YourServlet

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

I am sorry to tell you this, but if you are a beginer with java why do you write jsps? The code that you wrote has several errors, but not because of your lack of effort. Because there some things that you have confused and you need some studying to do first before start writing. The code will not work the way you "imagine" that it will work. You write html and javascript and assume that it will behave like java does:

<INPUT NAME="GIRL">
That is not how you declare variables in html and you cannot reference it like this:
document.write ("Take "GIRL" to the "PLACE" on "DAY);
because there aren't any variables in html that you can call at "runtime"

The function PickDate is written in javascript and you are trying to call java methods in it.

You are trying to write html as if you are writing java in a main method.

From your code one can understands that you have confused a lot of things about the differences between java - html - jsp - javascript and it will not help you learn if someone just writes it for you.

As hiddepolen stated - while I was preparing this post - what you are trying to do can be done with pure javascript. You need to declare the html tags correctly and use the apropriate javascript in the PickDate. You are also trying to use java in the html …

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

The encryption takes place in the servlet not when you submit the page. You pass the password the user entered from the gui, so the password at the url is unencrypted. It goes to the servlet where you do the encryption.

There is no way to avoid that. (Actually there is but it is needless).
What people do is use:

<form name="form1" method="POST" action="LoginServlet" onsubmit="return checkForm()">

method="POST"

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Embedded Google translator should solve it. What you think javaAddict?

It looks interesting. Maybe not like how the OP would have imagined, but if it does the trick, it's up to the poster's choice.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Have the System.out.println("Number of tosses\t\tNumber of Heads\\ % \t\tNumber of Tails\\ %"); before the loop.

Loop 500 hundred times. Every 30 times, print the System.out.printf("\t%d\t\t\t\t%d %d\t\t\t\t%d %d", frequencyHeads + frequencyTails,frequencyHeads,percentageH, frequencyTails,percentageT); in the loop

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

You don't call the actionperformed. It is automatically called whenever you click a button.
You implement it normally in the same way you do when you use javax.swing. Your applet should implement the ActionListener interface, then you will declare the actionPerformed method and write code inside it. Then you will add to your buttons that ActionListener (namely the applet like you do with normal java GUI).

If you want to call the actionPerformed method explicitely meaning you want to call the code inside in some cases, I would suggest to either call directly the code you put inside the actionPerformed method, or trigger the button clicked yourself. The JButton class has a doClick method for that purpose

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Do you have any code? The assignment that you posted is actually an explanation of what you need to do:

"Data fields for your instrument should include number of strings, an array of string names representing string names (e.g. E,A,D,G), and boolean fields to determine if the instrument is tuned, and if the instrument is currently playing."

Create a class that has the above fields. Follow the instructions to create your classes and methods. You don't need to think anything.

If you have errors post your code.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

@javaAddict: Thanks, I tried your code and it's working! I guess the problem is solved then. I don't get why i can't have "while (tallPosisjon <= famousFinalFour.length())" though, but I'll look into it.
Thanks everyone for your help, I'll mark this as solved

@Norm: aha, of course. Well I guess it's solved now anyway.

Because when tallPosisjon = famousFinalFour.length() it will enter the loop and you will call the:
famousFinalFour.charAt(tallPosisjon);

But indexes in java are from 0 to length-1. If a String has length 4 ("abcd") you can call:
charAt(0), charAt(1), charAt(2), charAt(3) but not charAt(4)

It like when you loop:

for (int i=0;i<array.length;i++) {

}

You don't use <=

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

So you are saying that the method kjennetegnErGyldig correctly returns false when you enter wrong data but when you enter the right data the loop doesn't go to the System.out.println("Årsmodell: "); call ?

If yes then maybe the problem is with the kjennetegnErGyldig method. Try to add more prints at the beginning and the end. Specifically before you return true. Have you tested it? Since it is static you can call it alone from a main method and see if it returns true.

My guess is that when it enters the last loop it never exits:

while (tallPosisjon <= famousFinalFour.length()) {
  if (! (famousFinalFour.charAt(tallPosisjon) >= '0' &&      famousFinalFour.charAt(tallPosisjon) <= '9') ) {
  System.out.println("De fire siste sifrene må være heltall mellom 0 og 9.");
  return false;
}
}

Look at it. If it enters the loop you have no way to exit. The tallPosisjon will always be lower than the famousFinalFour.length. Shouldn't you be increasing the tallPosisjon with each loop, so eventually the tallPosisjon <= famousFinalFour.length will become false?

while (tallPosisjon < famousFinalFour.length()) {
  if (! (famousFinalFour.charAt(tallPosisjon) >= '0' &&      famousFinalFour.charAt(tallPosisjon) <= '9') ) {
  System.out.println("De fire siste sifrene må være heltall mellom 0 og 9.");
  return false;
}
tallPosisjon++;
}

Notice the the check should be: tallPosisjon < famousFinalFour.length without the equals. If it is equal the charAt will give you an ArrayIndexOutOfBounds Exception.
The tallPosisjon should be from 0 till famousFinalFour.length-1

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster
responce .sendRedirect("user.jsp");

For single values that approach could work. You can use this:

String value1 = "aaaa";
String value2 = "bbbbb";

responce.sendRedirect("user.jsp?param1="+value1+"&param2="+value2);

At the jsp you can use this:

String param1 = request.getParameter("param1");
String param2 = request.getParameter("param2");

When sending data like that use the .getParameter. But that won't work if you have one instance of an object and you want to send the whole thing

If you want to send an instance of an object use this at the servlet instead of the sendRedirect

SomeObject obj = get_from_somewhere;
request.setAttribute("SOME_KEY", obj);

RequestDispatcher dispatcher = request.getRequestDispatcher("user.jsp");
dispatcher.forward(request, response);

At the jsp:

SomeObject obj = (SomeObject)request.getAttribute("SOME_KEY");
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

First, use code tags. Press the button CODE and put your code between the tags.
Also I tried running your code and it didn't work, even though it is correct. It behaves very strange and the debug gives me strange behavior. Finally I found the problem. When you write (me) something a lot of times, when you see it written you assume that it is correct, but in your case it is wrong:

I write:

for (int i=0;i<length;i++) 
{

}

You wrote:

for(ctr = 0; ctr < sentence.length(); ctr++);
{

}

Can you spot the difference:

for(ctr = 0; ctr < sentence.length(); ctr++);

We use the ';' to terminate commands. So when you put the ';' at that place you terminated the for loop. So only this got executed N times:

for(ctr = 0; ctr < sentence.length(); ctr++);

And then after ctr changed frm 0 to sentence.length() the following command executed outside the loop:

System.out.println(sentence.charAt(ctr));

So basically when you put that ';' at the end of the for loop you practically wrote something like this:

for(ctr = 0; ctr < sentence.length(); ctr++) {}
{
  System.out.println(sentence.charAt(ctr));
}

The for executes with no body. Then when the ctr is equals to sentence.length() exits the loop and executes one System.out.println(sentence.charAt(ctr)) which gives you an error.

Try running this and see what happens:

int i=0;
for (i=0;i<length;i++);
 System.out.println("i: "+i);

Then write this with no ';'

int i=0;
for …
Ezzaral commented: Helpful explanation. +15
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

The '=' is used for assignments. The '==' is used for comparison:

if(Btn2.getSelected() == true){
       
}

Or better if the Btn2.getSelected() returns boolean:

if ( Btn2.getSelected() ){
       
}

Edit: In your code you use Btn2.setSelected() . Perhaps you meant getSelected, because normally with set you pro-grammatically change the value

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Don't use random methods. This isn't the lottery. Use logic.
Since you are writing jsps, you know how to loop an array:

for (int i=0;i<array.length;i++) {

Why you set i to be 0 and i<length ? You pass the counter at the request and you use it as argument at the get method.
The list has elements from 0 till size-1, so the counter must be within that range. So display the next, previous links only when the value at the Counter parameter of the links is within that range

peter_budo commented: One for sticking with this guy, and hard time spoon-feeding :) +16
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

The declaration is wrong. There is no such thing as int void.
It is either int or void. And in this case it should be int:

public int countTokens(String s)
{
StringTokenizer st= new StringTokenizer();
return st.countTokens();
}
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

You should better remove the initialization of BufferedWriter outside the loop. Why you need it in? Each time you create a new one, you close it then create again a new one?
Put it outside the loop, in the loop call only the write method and close after the loop.
Understand what your code does.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

So you are saying that when you debug the messages:
Will read file , Done reading file appear
but when you run it, only the first one appears?

I would suggest the following. More debug messages:

File file = new File("projects");
// print the file
// print if the file exists: file.exists()
JOptionPane.showMessageDialog(null, "Will read file", "clear.", WIDTH);
FileReader input = new FileReader(file);
JOptionPane.showMessageDialog(null, "Done reading file", "clear.", WIDTH);

And at the end add another exception:

private void readFileButtonActionPerformed(java.awt.event.ActionEvent evt) {                                               
        try {
            // ...........
        } catch (ArrayIndexOutOfBoundsException e) {
            /* If no file was passed on the command line, this expception is
            generated. A message indicating how to the class should be
            called is displayed */
            JOptionPane.showMessageDialog(null, "Unable to open Project file. (IOOB)", "Error: Contact Programmer.", );

        } catch (IOException e) {
            // If another exception is generated, print a stack trace
            JOptionPane.showMessageDialog(null, "Unable to open Project file. (IO)", "Error: Contact Programmer.", );
            e.printStackTrace();
        } 
// add this
catch (Exception e) {
            JOptionPane.showMessageDialog(null, "Final error: "+e.getMessage(), "Final Error", );
            e.printStackTrace();
        }
    }

You will also need to check the console or the IDE output when you run it in order to see the printStackTrace or any other messages you print using the System.out.println

JOptionPane.showMessageDialog(null, "Unable to open Project file. (IO)", "Error: Contact Programmer.", WIDTH);

The WIDTH is not correct. Just because it got auto completed from the IDE doesn't mean you should blindly follow it. Check the API of JOptionPane class and check that …

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Firstly the requirements say that you shouldn't append the results to the new files so don't use the true option:
FileWriter fstream = new FileWriter(filename,true)

Second if you have been taught to use the PrintWriter then use that.

You can use the BufferedReader to read from a file or you can also use the Scanner class. if you pass as argument to its contructor a File object.

As far as your Studnet class: JPleasant_Project#1
You have been told to create a Student class not a JPleasant_Project#1 class.
Also the name,hours,grade need to be the attributes of the class, not local methods inside of a main. Don't put a main inside the Student class. Just the attributes with get/set methods. Surely you have been taught how to create custom classes.

You will use code to write in the new files. That code would be put in the if-else statements and according to each case you will write to the file described by your requirements.
Create different writers outside the loop with the students and use their instances to write to each file.

The code provided by jeffery12109 was just an example. you need to make the right modifications or whatever way you have been told to use

------------------
If your teacher hasn't told you how to create custom classes then things are to become more complicated, because you need in the same main, do the reading and while reading writing …

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Okay is there any steps you can give me to work on I know I have to create the candidates.txt, cumlaude.txt, magna.txt, summa.txt, noGrad.txt, hoursError.txt and gpaError.txt. Do I put the if statments above by name into these cumlaude.txt and what more do I need to assign to String name; double hours; double grade;... We get all this from the user so its unknown correct? I just need help. Steps, procedures, anything..

You have already been given the first steps to start at my first post.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Don't put everything in the main method and don't write everything at once.
First create a Student class with attributes: name, hours, grade.

Then have a single method:
In that method read the file with the students and have the method return a list with the data. The List will have Student objects

First write that method test it and then you can call it, loop the list and have if statements in order to determine which student to write to which new file.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Can you post the code you used?

Or you can search this forum for examples on how to run queries at a database and get the results.
Remember, put that code in a separate method in a class and call that method from wherever you want. That method should return the data you want to display.

And try to avoid roseindia

kvprajapati commented: +1 Good suggestion. +15
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

You don't need the commit command. It is done automatically, unless specified otherwise.
Also try to print the query and what actually gets executed.
Also the executeUpdate returns an int value. It shows how many rows have been updated/inserted. Try to print that too.
Also your catch block is empty. Why? That is problem. If you have an exception, you print nothing and you don't know if something went wrong.
You also need to close the connection as well as the Statement.
And it is better not to use the from.toString() . If you want to save the address, try to use: from.getMailAddress() or something. Because toString is used for displaying and maybe in the future you decide you want to change the way the object gets displayed. But since you need to save in the DB only the email, then you need to get the email.

import java.io.*;
import java.util.Properties;
import javax.mail.*;
import java.sql.*;

public static void insertm(int mid,Address from,String sub){
    
try {
    // Load the JDBC driver
    
    Class.forName ("oracle.jdbc.OracleDriver");

   Connection conn = DriverManager.getConnection
            ("jdbc:oracle:thin:@//localhost:1521/xe", "scott", "tiger");
                           
       
        Statement stmt = conn.createStatement();
      String str = from.toString();

System.out.println(sub+", "+str+", "+mid);  
//sql      
        String sql = "insert into mms(subject,pno,mid) values ('"+sub+"','"+str+"',"+mid+")";

    System.out.println("Executing: "+sql);    

    int i = stmt.executeUpdate(sql);
       
    System.out.println("Rows Updated: "+i);   

     stmt.close();
     conn.close();
} catch(Exception e) {
   System.out.println("Error: "+e.getMessage());
   System.out.println("Details: ");
   e.printStackTrace();
}

The next step would be to move the close commands in the finally block:

....
try {
   ....
} catch (Exception e) {
   System.out.println("Error: …
mKorbel commented: finally block, +1 PreparedStatement ??? +8
andreson commented: problem solved +0
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Thank you for your feedback. Ok, I made it so that it takes in any number of arguments, but I kept the try-catch block just in case someone enters a non-numerical argument.

That is good thinking! But is best to user the NumberFormatException. Again with this code if you have an exception other than "the user has entered non numeric" you will display the same message. In this case, you are correct. Nothing else would be thrown.
Your code works.

But in case you don't know about the NumberFormatException it is the exception that you get when you try to call the Integer.parseInt with non numeric values.
So you could alter your code like this:

catch(NumberFormatException nfe) {
  System.out.println("You may have entered a non-numerical argument: "+nfe.getMessage());
}

And as NormR1 said:
Also I think that you should check that happens if the user doesn't enter any arguments. In this case, arguments will have length zero and you will have an exception when you try to divide in order to get the average.
You could add an if statement at the beginning checking if the length of the args is positive

jamd200 commented: Thank you for you help. - jamd200 +1
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

If I may add, I don't believe that the approach of using a try-catch for handling the length of the arguments is correct:

catch(Exception e)
		{
			System.out.println("There can only be four arguments entered for this program.");
                        System.out.println("At the next prompt in this command line,");
			System.out.println("enter 'java Test' followed by the four (and only four) arguments");
			System.out.println("that you want to enter for this program.");
		}

In this case it is ok, but in general no. For example. With the above code you catch all the exceptions: catch(Exception e) { Meaning that if some other exception happens you will still display the same message. In this case of course I don't see any other possible exception caught, but it is not correct to ignore the exception instance 'e'.

Also you should never catch exceptions that can be avoided such as ArrayIndexOutOfBoundsException. You know that this exceptions happens when you try to access arrays, but I have never seen anyone loop like this:

int [] array = new int[4];
try {
  for (int i=0;i<1000000000;i++) {
     System.out.println(array[i]);
  }
} catch (ArrayIndexOutOfBoundsException e) {
}

A better approach would be:

if (args.length!=4) {
  System.out.println("There can only be four arguments entered for this program.");
  System.out.println("At the next prompt in this command line,");
  System.out.println("enter 'java Test' followed by the four (and only four) arguments");
  System.out.println("that you want to enter for this program.");

  System.exit(0);
}

int[] arguments = new int[4];
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);

..

Also NormR1 is correct at …

NormR1 commented: Nice details.I was too lazy. +12
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Cross posted in this thread:
http://www.daniweb.com/web-development/jsp/threads/75973

Do you have a question?

The right way to do things:
http://www.daniweb.com/web-development/jsp/threads/141776

The wrong way was just posted in this thread.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

i need jsp and servlet coding for login page where the username and password must b stored in a db table

And I want vacation.
Sorry I thought that this thread was for posting what we want but you won't get!

Seriously:
This thread is very old. If you have a question start your own. And no one is going to give you the code. We don't give code like that. If you don't have a clue start studying and search for examples in this forum. Post what you have done.
You need to know basic java, connecting to the database and running queries, sql, html and jsp. What do you know from the above?

And separate your methods in different classes. Don't put code that connects to the database in the jsp page.
Once you post what you have done you will get help.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

I tested your code and couldn't get it to work. The buttons weren't displayed.
I would advise you not to use the paintComponent. It it used to paint graphics (circles, images, lines, ....)
You don't need that method to add buttons and other components such as JLabels

Try putting the code of the ButtonPanel in a constructor:

....
....
	private class ButtonPanel extends JPanel
	{
            public ButtonPanel() {
                JButton redButton=new JButton("Red");
                JButton yellowButton=new JButton("Yellow");
                JButton greenButton=new JButton("Green");
                
                add(redButton);
                add(yellowButton);
                add(greenButton);
                
                ColorAction setRed=new ColorAction(Color.RED);
                ColorAction setYellow=new ColorAction(Color.YELLOW);
                ColorAction setGreen=new ColorAction(Color.GREEN);
                
                redButton.addActionListener(setRed);
                yellowButton.addActionListener(setYellow);
                greenButton.addActionListener(setGreen);
            }
                /*
		public void paintComponent(Graphics g)
		{
			
		}
                */
	}
....
....
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

By using proper html. You align in the same way you would have aligned them if they weren't select tags.
Do you use table tags? If yes then there is something wrong with your td,tr tags. Try to add the border="1" attribute at the <table> and see what is going on.

<table border="1">
  <tr>
     <td>Line 1 Col 1</td>
     <td>Line 1 Col 2</td>
  </tr>
  <tr>
     <td>Line 2 Col 1</td>
     <td>Line 2 Col 2</td>
  </tr>
</table>
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

that doesn't help at all , it works on my netbeans ide 7.0.

Net beans is an IDE. It has nothing to do with the code. If the code is correct it should work no matter how you run it.
Also if the code was given to you and you haven't written, shouldn't you ask the one that gave it to you for explanations?

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

When the page loads or gets submitted the java code executes. After the code executes the html gets displayed. If you want to execute java code when you click a button you need to submit to the page where the code is. If you want that page to be the same then submit to the same page, but make sure that the code gets executed only when you submit. So here is a small example:

... html code

<%
String submitted = request.getParameter("submitted"); // the first time the page loads this is null:

String name = "";

if (submitted!=null) { // if you submitted to this page then this is not null

  // create an instance of your class
  // call its methods
  // take the data from the DB
  name = "some data";
}
%>

<form action="pres.jsp">
  ..
  <td>Name: </td>
  <td><%=name%></td>
  ..
</form>

<form action="">
  <input type="submit" value="Generate" >
  <input type="hidden" value="1" name="submitted" >
</form>

When action is empty it submits to the same page.

I would advise you to create a custom class with attributes the columns of the table and have your method that reads from the DB return that

In general I would advise you to change your logic. I don't know what you are trying to accomplish, but it would be better if you had one page where the user can insert data to the database and another where the user can view the data.
Maybe you can add input fields that …

arshi9464 commented: superb programmer and logic builder. +2
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

1 class -> 2 methods.
1 method that inserts
1 method that reads.
Call those methods from the jsp.
Create a class that saves the data as attributes.

The rest of the code is wrong. The java is executed at the server. The javascript at the client. So when you click the pat function, it will not execute the java code that is inside it. That code has already been executed, when the page loaded.
If you want to execute java code, you need to submit the page, execute the java, take the values and display them. You can use javascript to submit the form though.
You can put the "Generate" button in its own little form and submit it to itself.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Read the error messages that you get. The method "findBiggest" returns a Rectangle. So why do you assign it to an array when you call it.

Also you cannot use: '>' with objects: if(rects[i] > biggestSoFar) If you want to compare them based on their area, then call the getArea() method in order to compare the area of the rectangulars

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster
<td colspan="3"><input name="text4" id="vid" type="text"/></td>
                    <td colspan="1">
                        <select name="combo1" onchange="document.getElementById('vid').value=this.option[this.selectedIndex].text">
                            <option>Select One</option>
                   <%
                   stmt=con.prepareStatement("Select id from student order by id");
                   ResultSet rst=stmt.executeQuery();
                   while(rst.next())
                       {
                    %>
                            <option><%=rst.getString("id")%></option>
                     <%
                   }
                   }
                  catch (Exception e)
                   {
                       System.out.println("error in program:-"+e);
                   }
                   %>
                        </select></td>

hope it might work for u..

That code is completely wrong. Don't give advices if you don't know what you are doing. For starters you don't close anything. Zero re-usability. You don't set the value attribute of the options tag so what's the point of having a select box and the user doesn't gets notified if an exception occurs!

Everything needs to be in its own class with a method that returns the values of the select box in a list or an array.
Then in the jsp you call the method and loop the list. Also inside the list/array, there should be an object with attributes for the value of the option as well as what would be displayed.


--- Create a method that retrieves the data from the database and returns them. Call that method from a main method and test it. Once you are done, you can call it in the jsp. You can post the method if you have any problems with the code. Get it done and afterward you will deal with the jsp/presentation part.

kvprajapati commented: words :) +14
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Wow, nice.. That's pretty cool. Makes the code in the files less and much more manageable. In the myHtml.jsp, you don't need to import anything like that? You literally just do this:

<%
     String s = (String)request.getAttribute("attr1");
     Integer iObj = (Integer)request.getAttribute("attr2");
%>

And the request/attribute data will be "reachable" for the jsp page?

Yes,
But of course you need to have set those values in the request. Otherwise they will be null.
That is happening when you do this: dispatcher.forward(request, response); You set the attributes at the request instance and send that request to the jsp page of the dispatcher

peter_budo commented: Thank you for helping out +16
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

So what you saying. Is that instead of having a single servlet generate 3 "html pages".. Rather have 3 servlets that obtain data from the database etc, and 3 JSPs that then uses those 3 servlets repectively?

Actually I had a problem with the browser reloading that is why my first post didn't make much sense. Read my latest post.

Also
You can do whatever you want based on your needs.
Example:
After reading your last comment, you can have 1 servlet that redirects to whatever html you want:

String url = "";
if (....) {
  url = "somepage.jsp"
  request.setAttribute("att1", "value1")
} else if (....) {
  url = "somepage2.jsp"
  request.setAttribute("att2", "value2")
}

RequestDispatcher dispatcher = request.getRequestDispatcher(url);

dispatcher.forward(request, response);

You don't need to have 1 servlet for all pages. You can have 1 servlet that goes to 1 jsp page,
Or 1 servlet with if statemets that goes to many pages.

Many similar pages that have some sort of common operations so they need to go the one servlet that has the code you want to execute and redirect to wherever you want.


BUT. I general: HTML code in servlets: bad idea. I am sure that you already know that; after trying to write html code like this:

PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<head><title>Servlet1</title></head>");
        out.println("<body>");
        out.println("<p>Hello world</p>");
        out.println("</body></html>");
        out.close();

Imagine wanting to write a huge jsp page with many tags and complex javascript code. Even the above is difficult to understand, write …

Dean_Grobler commented: Right to the point, easy to understand explination. Well done! +1
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Is this line 19:

if(first.next == null) { //this line 

If yes then according to the exception you are trying to use something which is null. In this case I assume that it is the "first"

I don't know your logic but, maybe you need this:

if(first == null) {
  ...
} else { ...

OR

if(first == null || first.next==null) {
  ...
} else { ...

In any case you need to check if "first" is null and/or first.next before you use either one.

And use code tags. Press the button (code) when you make your post

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Is this the exact code that you use?
Because string needs capital S and system, needs capital S:

class forloop {
  public static void main(String args[]){
   int x;

   for(x=0;x<10;x=x+1)
    System.out.println("this is x:"+x);
   }
}

How do you compile the .java file?

Also for future references, you should name your .java files with capital letter:
ForLoop.java

class ForLoop {

}

It is common practice.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Actually, I think, that "import a method" is just a fancy way of saying, I want to call a method of a class from somewhere else:

class MyUtils {
  public MyUtils() {

  }

  public static void method_1() {
    // ........
  }

  public void method_2() {
    // ........
  }
}
// SOME WHERE ELSE - ANYWHERE YOU CAN CALL METHODS (even in another class)

// CALL STATIC METHOD:
MyUtils.method_1();

// CALL NON STATIC METHOD:
MyUtils myUt = new MyUtils();
myUt.method_2();
myUt..........

In your case you can have a method that takes as argument a Foot instance and an int, and call the turn method.

zach&kody commented: Thanks! +0
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

send me the code of these

Using two dimensional array in java write program to print following Pascal triangle.

1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

We don't give away code. We help those who are willing to learn.
Start a new thread, and post what you have done so far.

And we don't work for you to order us: "send me the code of these"

HINT: Each line has the same amount of numbers
First line has 1 (one number), Second line has 1 1 (two numbers), Third line has 1 2 1 (three numbers)
Use 2 for loops one inside the other

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

You didn't read carefully! If you had, you would have seen that that method, is declared to be void. Meaning that it doesn't return anything.
So when you do this: Rectangle box3 = box.translate(40,30); You get an error because translate has return type "void". It doesn't return anything. It translates the instance that you call it: "box". Just call it. It is is void. Like you call any other void method. And then print the box

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

This is a small summary of your code:

Term term = new Term();
while () {
    if (str exists) {
      // don't add
    } else {
      // add term
    }
}

The problem is that term is declared outside of the while. So you do new Term() once. You created only ONE instance. So when you put into the Map bagOfWords the 'term' you put the same term with each iteration.
Example:
The first time you add for example the 'i'. That is the value of the instance term.
At the second time, you put the 'car' like this:

term.term=str;
bagOfWords.put(str,term);

BUT that 'term' is the same instance that had the first 'i'. So since it is the same instance in the memory, you changed its value. The MAP had this inside:

'i', term='i'

When you did this at the second time: term.term='car', you change the value that the term has. But that term is the same as the one already in the map. So every time you do this term.term=str, you change the value of the term instance which is the same term set for all the keys in the MAP.

'i', term='car'
'car', term='car'

Then:

'i', term='collision'
'car', term='collision'
'collision', term='collision'


So every time you want to add a new term, then create a new instance:

public void makeDictinary(String str,int i){

// REMOVE THIS		
//Term term=new Term();

str=str.toLowerCase();

....

else
		        { …
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Buy a book, read a tutorial. How can anyone explain what you ask in a single post. What you ask is for someone to quote pages of books in a single post.

Buy a book, read a tutorial. Write some code, compile it, deploy it. Use an IDE that does that for you. Perhaps NetBeans.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

What do you want to build? Where do you want to work?

kvprajapati commented: Thanks Mate! Unique way to report :) +11
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Whether you are professional or student is irrelevant. The fact that you are new in Java means that this is too much for you. No one that is new in Java can deliver what you have been asked to do. What you have been asked is not for beginners.

I am not the best in java but not a beginner either. But I don't know how to do this and if I had to, I would do a lot of search and studying. There are many examples and tutorials and libraries that do what you want with little code and effort on your behalf.

Start searching and coding.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Actually the code that you wrote is logically wrong. If you don't want to redirect then the searchTerm must be null OR searchTerm.length==0. not AND
You will not get a NullPointerException if you write it correctly:

if (searchTerm == null || searchTerm.length() == 0) {
  // don't redirect.
}

That is the opposite of my if.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

So from what I understand, you have a form and you submit to a page. But if the form is empty you want to go back to the form? Wouldn't be better if you didn't submit the form in the first place?

<HTML>
<HEAD>
<script>
  // javascript method. Executes at the client. No submit takes place
  function validate() {
    var sT = document.myForm.searchTerm.value;
    if (sT=="") {
      alert("PubMed is empty");
    } else {
       document.myForm.submit();
    }
  }
</script>

</HEAD>
<BODY>
  <FORM METH0D="GET" action="index.jsp" name="myForm">
  <INPUT TYPE="TEXT" NAME="searchTerm" /><BR/><BR/>
  <INPUT TYPE="BUTTON" VALUE="Search PubMedX" onclick="validate();" /><BR/>
  </FORM> 
</BODY>
</HTML>

An alternative to that would be not to have javascript at all and submit to the same page. When action="" then you submit to the same page. Then use java to check the input field and then redirect:

<HTML>
<HEAD>
</HEAD>

<%
String searchTerm = request.getParameter("searchTerm");
if (searchTerm!=null && searchTerm.length!=0) {
  // redirect to the next page
%>
   <jsp:forward page="index.jsp" />
<%
}
%>

<BODY>
  <FORM METH0D="GET" action="" name="myForm">
  <INPUT TYPE="TEXT" NAME="searchTerm" /><BR/><BR/>
  <INPUT TYPE="SUBMIT" VALUE="Search PubMedX" /><BR/>
  </FORM> 
</BODY>
</HTML>

The first time the page loads, the searchTerm is null, so from the if nothing happens. If you submit, then the same page loads but this time the searchTerm is not null. In any case the if will always run and if the searchTerm exists and it is not empty, you redirect.

You <jsp:forward /> you don't have to worry if the searchTerm is in the request, because it is. Even if you …

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Have you tried if(saw == "") ?

martin5211 please, If you don't know what you are saying don't post wrong advices. Be sure about what you post and test it before you post it.
Don't use ==. Never use ==.

The problem is that if you don't enter anything at the text field, it will return an empty String, not null.
It will return null if the searchTerm doesn't exist in the request, meaning if you didn't have such field.

Try and write this:

String abc = request.getParameter("some_crazy_string_12312312");

abc will be null.
But if you have searchTerm as a field and you don't enter anything then you will get what you passed which is an empty String "".

Also this is totally wrong:

String see ="null";

see is NOT null, it is "null". null means it doesn't exist. "null" means it has the value of the String "null". When null you cannot use it to call methods.

You cannot do this: You will get an exception:

String s = null;
s.length();

But this will return 4:

String s = "null";
s.length();

Study a bit more about jsp. Your methodology is wrong. Don't use out.print() . Use scriplets.
Don't use servlets to write html code. Change this:

out.print("<br/> <br /><B>Please enter a term to search on NCBI<br /> PubMed:</B><BR><BR>" );
out.print("<FORM METH0D=GET action =\"index.jsp\">");
out.print("<INPUT TYPE=TEXT NAME=searchTerm><BR><BR>");
out.print("<INPUT TYPE=SUBMIT VALUE=Search PubMedX\"><BR>" );
out.print("</FORM> " );
out.print("</BODY>" );
out.print("</HTML>");

To this:

<br/> <br /><B>Please …
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

First of all.
You don't need this:

onsubmit="javascript:return onClick()"

The javascript: is used only if want to execute javascript when you click a link. For simple events use:

onsubmit="return onClick()"

Second. You have everything in your first form, but the button that submits it is in another form. You have this:

<form name="form1" action="Details.jsp" method="post" onsubmit="javascript:return onClick()" >

....
  <input id=submit1 type=submit value=Submit name=submit1>

<form name="form1" action="PageTwo.jsp" method="post">
</form>

You open a form tag, you don't close it and inside it you open-close another.
You should have everything you want to submit in ONE form:

<form name="form1" action="Details.jsp" method="post" onsubmit="return onClick()" >

....
  <input id=submit1 type=submit value=Submit name=submit1>

</form>

You can multiple forms if necessary but you must open-close them and each must have one submit button with its own data:

<form name="form1" action="page1.jsp">
  ... input tags ...
  <input type="submit" name="subm1" value="Submit 1">
</form>

<form name="form2" action="page2.jsp">
  ... input tags ...
  <input type="submit" name="subm2" value="Submit 2">
</form>

When you click submit1 then the first form will be submitted and if you click the submit2 the second form will be submitted.
But you need only one. So keep your code and have one form that opens/closes with one submit button.

Now after you submit to another jsp or servlet, you can take the values entered like this:
Put this code to the jsp or servlet that you submitted to.

String origin = request.getParameter("Origin"); // as argument use the name of the tag

Also in your code …

peter_budo commented: Good reply +15