javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

I have similar prob. The get attribute is null while the id is not null.
for my java:
if(session.getAttribute(abc)==null)
System.out.println(abc is null
else
System.out.println(abc is not null)

if(session.getId()==null)
System.out.println(id is null)
else
System.out.println(abc is not null)

Do i need to also use session.setAttribute(abc) in the jsp?

Start your own thread, be more descriptive, did you put it in the session?

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

It is like I said. You lack the very basics and you should be ready to accept criticism:

Java is executed at the server. Then the page is generated and then send to the client pure html.

Meaning that this:

onChange='[B]<%session.setAttribute("currentTable", request.getParameter("tableSelect"));%>[/B]; testForm.submit();'

is not executed then you change the drop down list.

Java and javascript ARE NOT THE SAME

Jave is executed at the server, the javascript at the client and it has absolutely NO access to java classes or objects.

When you submitted, you send to the server the request, then this is executed: session.setAttribute("currentTable", request.getParameter("tableSelect")); Then you receive at the client this:

<select name='tableSelect' onChange='testForm.submit();' style="text-align:center">

Only the 'testForm.submit();' will be executed at the onchange because it is javascript not java. The java part has already been executed when you submitted.

This works:

document.formName.inputName.value = '<%= (String)session.getAttribute("..")%>'

because first the java scriplet is evaluated and then sent to the client. What you actually see to your browser is this.

document.formName.inputName.value = 'theValueReturned';

No matter what you do, you cannot change a java variable if you don't submit.
So if you look only at your java code:

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Test Page</title>
    </head>
    <body>
        <%
            [B]String choice = (String) session.getAttribute("currentTable");[/B]
        %>
        <form method="post" name="testForm" action="Test.jsp">
            <select name='tableSelect' onChange='<%[B]session.setAttribute("currentTable", request.getParameter("tableSelect"));[/B]%>; testForm.submit();' style="text-align:center">
                <option value='--Select Table--' <%= ("--Select Table--".equals(choice)) ? ("selected='selected'") : ""%> >--Select Table--</option>
                <option value='CONFIG_SOURCE' <%= ("CONFIG_SOURCE".equals(choice)) ? ("selected='selected'") : ""%> >CONFIG_SOURCE</option>
                <option value='CONFIG_PROCESS' <%= ("CONFIG_PROCESS".equals(choice)) ? ("selected='selected'") …
peter_budo commented: Very truth, nice code provided +11
kvprajapati commented: Great explanation. +6
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

i was assigned to do a assignment which is to create a website selling movies.i used the GUI to create the "Add to Cart" button. But, i dont know how to code. I mean what should i code to let other people can click it to add the items they want to the cart??

Do you know jsp, or how to submit a request using form.
If yes then maybe you can have the button ("Add Cart") submit the form that has the items the customer has selected and after you retrieve them put their ids inside a cookies.
Or if it is required for the user to log in the session

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

I usually don't work with frame and I don't have time to give it much thought right now.
But, have you tried submitting the form to the jsp that is the second frame?

I assume you have a page where you declare the 2 frames and declare which jsps will be displayed.

My first guess would be to have jsp_1 to submit to the second jsp:

<form name="..." action="frame2.jsp" >
...

Firstly see if the drop down list in the first jsp stays unchanged, and if the value sent is printed.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Here is how:
1) Post to correct forum
2) Be more descriptive on your problem
3) Show some effort

If you are talking about a web application

4) Learn about request, session
5) Learn about cookies
6) Learn about MVC (find the tutorial at the jsp forum)

Do you have a working web application were the user can login and view the items?

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

DUNGEON ADVENTURE

Thanks for the idea. I have been wanting to create a game similar to this for fun, just to kill time, but couldn't get any smart ideas.
I will definitely build this and give it to my friends to play.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

What is the range of the random numbers? Because you can use the Math.random.
Check the API

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Given this: document.getElementbyName('myCombo').selectedValue = session.getAttribute("choice"); I simply advised you to study a little more before trying things that are out of your league. The above code is an example of not understanding how to integrate java code in html, which should be very basic. So I just said that you focus more on learning.

Also this is how is done according to your code:

<%
String choice = (String)session.getAttribute("choice");
%>

            <select name='myCombo'>
[B]<[/B]option value='' 
<%= ("".equals(choice))?("[B]selected='selected'[/B]"):""%> [B]>[/B]--Select Table--</option>

[B]<[/B]option value='OPTION1' 
<%= ("OPTION1".equals(choice))?("[B]selected='selected'[/B]"):""%> [B]>[/B]OPTION1</option>

[B]<[/B]option value='OPTION2' 
<%= ("OPTION2".equals(choice))?("[B]selected='selected'[/B]"):""%> [B]>[/B]OPTION2</option>
            </select>

Also if you give a better explanation on how you put the value in the session, I will be able to give a more efficient solution.
In your other post you pass a drop-down-list value through the request. Is this the same drop down list?
What does this value represent because we rarely put things in the session. Maybe you can send it through the request.

Can you provide a more descriptive explanation on what you are trying to achieve and what is your wider goal so we can provide some recommendations?

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

You cannot combine java and javascript that way. They are NOT the same:

document.getElementbyName('myCombo').selectedValue = '<%= session.getAttribute("choice") %>';

I see from your previous thread that you lack of lot basic knowledge about jsp and submitting requests.
I would suggest to take sometime to learn the basics, study a little and then continue.

Forgot the '' single quotes. It will not work without them

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

First of all request.setAttribute is void. It doesn't return a value to put it in a string.

Secondly:

They're both in the same folder. I also added method="post" on Page 1... When I change the selection on Page 1, it works, and it displays what I selected, then when I refresh Page 2, it says null.

You just said that it works. Then what is the problem? You cannot just go to a page, refresh it and expect to see data. You say you have Page1 and Page2. Which one is Test.jsp?
When you want to send data to a page you put it at the action. The request is sent to that page:

<form action="somePage.jsp" >

</form>

The data will go to somePage.jsp. This is where you put your code. That page could be even the same. It makes no difference. But the data will go only there.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

I can't see a problem with your page. Does the page submits? Does it go from page A to page B? Is the name of the Test.jsp correct and are the pages in the same folder?

Does onChange works? Should it be onchange?

Also you can try this: document.testForm.submit();

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

At the validation I believe that the seconds should until 59. For the hours you 23, 59. Why not the same for seconds.

For the extract when you multiply and then do a mod, you will get 0.

123 * 100 = 12300
12300 mod 100 = 0
12300/100 = 123

mod returns what is left from the division:
9 = 2 * 4 + 1
9 mod 2 = 1
9 mod 4 = 1

This is the time: 125345 (12:53:45)
In java when you divide an int with an int you will get an int:

125345/100 = 1253
1253 * 100 = 125300

125345/100.0 = 1253.45

So when you divide by 100 you have:
1253
The time is:
125345
1253
Think how can you get the seconds.

THEN:
1253 / 100 =
12
Now how can you get the minutes.

The 12 is the hours

tom.t commented: Very helpful. Thank you. +0
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

I want to prevent unathorized users to access directly using URL in my application

When the user logs in, do you put that user in the session?

String username;
String password;

// check the database to see if the user is valid.
if (yes) {
  request.getSession().setAttribute("USER",username);
}

When the user logs out do you do this:

request.getSession().setAttribute("USER",null);

And my suggestion would be to put this check in all of your pages:

String username = (String)request.getSession().getAttribute("USER");
if (username==null) {
  // unauthorized user
  // redirect to log in page
}
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

For the first problem the method would be:

public int calculateFactor(int a, int b) {
  ...
}

Inside you will do the checks described in the assignment. No explanation needed. The assignment tells you what to do and what to check. Surely you can understand by now how the '%' works.
Don't forget to check what happens if the 2 numbers are equal. You will still need to return one of the arguments, it doesn't matter which, since they are equal.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

For the second problem. You need the largest divisor? Then why start the loop from 1 and not from the number itself:

int n; // read from input using Scanner;
int maxDivisor = 1;

for (int i=n-1;i>0;i--) {
    if ( n%i == 0) {
         maxDivisor = i;
          break;
    }
}

Also a more efficient way is to have the initial value to be the number dived by 2.

Think about it, the number 100 will not be divided by 99, 98, .. or any of those numbers. It will not be divided by 51, but it will be by 50.
For 93 (93.0/2.0 = 46.5) you can start checking from 46 because none of the numbers above its half can divide it.

In java:
93/2 = 46
93/2.0 = 46.5

So this would work:

for (int i=n/2;i>0;i--) {
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Well I would use a double matrix:

String [][] ARRAY = {
   {"A", "B", ...},
   {"B", "C", ...},
   {"C", "D", ...},
....
}

Then for mapping the letters with the numbers in a quick way:

HashMap map = new HashMap(26);
map.put("A",0);
map.put("B",1);
...

The key is the letter and the value is the number. So when you have a letter, get the number from the map and you the index to use for the array

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

hi :)
for the first problem you could do something like this:

public class Mymath {

    public calculateFactor( int a, int b ) {
        if ( a < b && b % a == 0 )
            return true;
        elif ( a > b && a % b == 0 )
            return true;
        else
            return false;
    }
}

and for the second part see if this is any helpful :):

import java.util.Scanner;

public class Test {

	public static void main( String[] args ) {
	    Scanner in = new Scanner( System.in );
	    String goOn = "y";
	    int n, largest = 0;
	    do {
	        System.out.println( "Input an integer number:" );
	        n = in.nextInt();
	        
	        for ( int i = 1; i < n; i++ )
	            if ( n % i == 0 )
	                if ( i > largest )
	                    largest = i;
	        System.out.println( "Largest divisor: " + largest );
	        System.out.println( "Another input (y/n)?" );
	        goOn = in.nextLine();
	        goOn = in.nextLine(); //doesn't work in there's only one don't know why.
	        largest = 0;
	        
	    } while ( goOn.equals( "y" ) );
      }
}

Your first code will not compile and it is not java (elif)

The second is totally inefficient and shows no thinking at all to the real problem

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Why don't you use the post method?

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Given your description (the lack of description that is), you may use a System.out.println.

BestJewSinceJC commented: uppity since this kid down voted +4
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

------------------------------------------------------------------------------------------------MY CODE-------------------------------------------------------------------------------------------------------------------------------------------------------


<%@ page import="java.sql.*" %>
<%@ page import="java.io.*" %>
<html>
<head><title>JSP Page</title></head>
<body>

<%
String school = request.getParameter("name");
String name = request.getParameter("username");
String email = request.getParameter("txtEmail");
String pass1 = request.getParameter("pass1");
String pass2 = request.getParameter("pass2");

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:shobana", "SYSTEM", "nagalakshmi");

Statement st = con.createStatement();

String sql = ("INSERT INTO register VALUES ('" + school+ "','" + name + "','" + email + "','"+ pass1 +"','"+ pass2+"') ");
st.executeUpdate(sql);
con.close();

%>
connection succssful
</body>
</html>

And what is the point of this post? This is a 4 year old thread which has been revived 1 year ago, with no useful information. Can someone please close this?

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster
public class testAssert { 
          public static void main(String[] args) { 
                  int x = 5; 
                  int y = 7; 

                  boolean b = x!=y;

                  System.out.println(b);
          } 
  }
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

First of all when you have questions such as this, always search the API.

http://java.sun.com/javaee/5/docs/api/javax/servlet/http/HttpSession.html#isNew()

http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/http/HttpServletRequest.html#getSession(boolean)

From the create session method, you see that it doesn't always create a new session. That call is the same as the no argument getSession() . The only difference is when you enter false. Then if there is no session it returns null.
But if you put true, it will not create a new session if one already exists.

I know that the above might no solve your problem because I just quoted the API, but have you tried running the session.invalidate() method first?

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

First of all you don't need to have 2 Scanner classes. One would be enough and you can call its methods as many times as you like in order to read as much input as you want.


And to VernonDozier,

the thread is this:
http://www.daniweb.com/forums/thread234373.html
Check posts numbers 16, 17.

The code I gave was this:

if (fnum is in range) {
  if (second num is in range) {
     // calculate the ouput
   } else {
     // print second num not in range }
} else {
      // print fnum is not in range
}

Only one pair of 'ifs'.

This is the original question:

JavaAddict,
Thanks, I see I what I have missed. Btw. I was trying to workout some random online exercises about the scanner, I have done some easy one except this one:
Write a program to input two numbers using Scanner class, the first number in the range 1 to 13 and the second number in the range 1 to 4. When the numbers are entered check that they are in the correct range. If not issue an error message using println().
Output the card face (or type) for the first number and the suite for the second number.
Your output should have a message such as “Queen of Diamonds” for the input of 12 and 2. The Ace of Diamonds would be 1 and 2; the Ace of Clubs would be …

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Actually I understood that the objective was to monitor how many times a word appeared.
I would suggest sth like this:

String word;
Vector linesAppeared;

And the size of the vector would be how many times the word appeared.

You must notice that from the code given, the words that the OP wants to search for are predetermined. And originally he was searching for the frequency of their appearance.
The reason I didn't want to go into the OO solution was the novice level of the poster, and I wanted to stick to the solution that he thought.


Thanks for your congrats remark
Of course if

BestJewSinceJC commented: actually agreed - the extra class may be more confusing than anything +4
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster
int lineCount = 0;
while(scanner.hasNext()) {
     lineCount++;
     System.out.println("Line "+lineCount+" is: "+scanner.next());
}

So have a Vector for each word
When the word is found, add to the word's Vector the line number.

Vector vIf = new Vector();

....
// inside the while loop
if (line.equals("if")) {
   Freq[1] = Freq[1] + 1;
   vIf.add(lineCount);
}

You don't know how many are the lines that contain the "if". So you have a vector and whenever an "if" is found you add to the vector the line number (count).

for (int i=0;i<vIf.size;i++) {
     System.out.println("The 'if' found at line: "+vIf.get(i));
}

Meaning that you don't need the Freq array because the size of the vector would be the numbers the 'if' appeared.


But you might need an array of vectors to make your program more advanced:

Vector [] vArray = new Vector[13];
for (int i=0;i<vArray.length;i++) { // vArray is an array
   vArray[i] = new Vector(); // vArray[i] is a vector. You need to initialize each element
}

and in your if statements you can skip the Freq. Instead of increasing it, replace it with the array of Vectors

if (s.equalsIgnoreCase("a") )
   //Freq[0] = Freq[0] + 1;
    vArray[0].add(count);
else if ( s.equalsIgnoreCase("if") )
   //Freq[1] = Freq[1] + 1;
    vArray[1].add(count);

Now the size of each Vector tells you how many times a word was found and their elements tell you at which lines they appeared.


PS.: This is my 1500th post! Yeeeees.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Both of your posts mean nothing to us:

first curly brace in the first.addActionListener
they start at line 424 and then at every first "{"

Do you want us to search that chaos of yours in order to find the "first curly brace"?
or do you expect us to count 424 lines?

Post relevant code where you point where is the error at what that error is.

Also the simple way for ActionListeners:

class MyFrame extends JFrame implements ActionListener {
   JButton b1;
   JButton b2;
....

   public MyFrame() {
       ....
       b1.addActionListener(this);
       b2.addActionListener(this);
   }

      public void actionPerformed(ActionEvent e) {
          Object source = e.getSource();
          if (b1==source) {
                 // b1 button clicked
          } else if (b2==source) {
                 // b2 button clicked
          }
      }
}
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

At what line you get the error and what does it say and at which class?

You probably haven't defined the actionPerformed method.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

First of all...Keep in mind...What do u want to do and display in window...
Because u have two varibles initialized with zero
then totalfeet= inches*12;
It means totalfeet=0*12;
which results total feet=0
And u r not displaying totalfeet
You are displayig 5*12=60

...
Put up correct question..so that we can help u

That question has already been answered.
This thread has 19 posts and you went and read only the first and skipped the rest?

Put up correct question..so that we can help u

Like I said, if you read the rest of the thread you will realize that your answer has nothing to do with the rest of the questions asked.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Don't loop like this:

for(int row=0; row<5; row++){
for(int col=0; col<3; col++){

Always like this:

for(int row=0; row<array.length; row++){
for(int col=0; col<array[row].length; col++){
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

You know very well that this is not the way to declare variables:

int firstnumber = 1,2,3,4,5,6,7,8,9,10,11,12,13;
int secondnumber = 1,2,3,4;

If you can't fix this, don't go any further.

This is how you read a number

System.out.println("Enter firstnum: ");
int fnum = QueenOfDaimond .nextInt();
System.out.println("Firstnum: "+fnum);

Do the same for the second number.

Use if statements to check the numbers:

if (fnum is in range) {
   if (second num is in range) {
       // calculate the ouput
    } else {
        // print second num not in range
    }
} else {
 // print fnum is not in range
}

If you don't know cards then:
1: Ace
2: two
....
11: Jack
12: Queen
13: King

As for the colors:
Hearts, Spade, ... and I don't know the english names of the rest
You can do any type of mapping for those.

As for the if and switch statements, that is up to you.
You should know how to write a simple if statements or how to use the '>' or the '<' operator, as well as the '&&' and the '||'.
If not, I can not teach you these thinks, you need to study for yourself.

Also search for the sun tutorials to find how to work on a switch. You should be able to find an example

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster
First it will calculate what is inside the parenthesis and return it. Then it will concatenate it with the rest: 
System.out.println("(a)" + [B]([/B]1 + m[k][B])[/B] );

// "(a)" + (1 + m[k]) --> "(a)" + (1+2) --> "(a)" + 3 --> (a)3
and 

// no parenthesis. Things will be calculated with the order they appear
System.out.println("(a)" + 1 + m[k] ) ;

//                     [U]String + int[/U]   --> [U]String[/U]       
// "(a)" + 1 + m[k] --> [U]"(a)" + 1[/U] + 2 --> [U]"(a)1"[/U] + 2 --> (a)12

In math they teach us first to calculate the parenthesis.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Read the comments

int m [] = { 3, 2, 5, 2 };
int k = 0;

// k has value 0 so it returns 3. THEN k is increased because the ++ is after the variable
System.out.println("(a)" + m[ k++ ];

// k has now value 1

// ++k. The ++ is before the variable so the increase will happen FIRST. So k will become 2. THEN k will "return" its value which is 2
// m[2] = 5
System.out.println("(a)" + m[ ++k ];


// it compiled..but i dun understand why is the result 3 and 5 respectively???

Try running this:

int k = 0;
// first prints then increases
System.out.println("K before the increase: "+ (k++) );
System.out.println("K now: "+ k );

k = 0;
// first increases then prints
System.out.println("K after the increase: "+ (++k) );
System.out.println("K now: "+ k );
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

If you search the net with: "ActionListener" you will receive plenty of examples:
http://java.sun.com/docs/books/tutorial/uiswing/events/actionlistener.html
I took an example from that page and modified it to be more simple for you:

import javax.swing.*;
import java.awt.event.*;

public class AL extends JFrame implements [B]ActionListener[/B] {
	JTextField text = new JTextField(20);
	[B]JButton b = new JButton("Click me");[/B]
    JPanel panel= new JPanel();
    
	private int numClicks = 0;

	public static void main(String[] args) {
		AL myWindow = new AL("My first window");
		myWindow.setSize(350,100);
		myWindow.setVisible(true);
	}

	public AL(String title) {
		super(title);

        panel.add([B]b[/B]);
        [B]b[/B].addActionListener([B]this[/B]);

        panel.add(text);

        add(panel);
	}

	public void [B]actionPerformed[/B](ActionEvent e) {
                // For debugging purposes. Just to show how you can find which button was clicked in case you have more than one.
                /*
                Object source = e.getSource();
                if (source==b) {
                    System.out.println("The button b was clicked: "+source);
                }
                */
		numClicks++;
		text.setText("Button Clicked " + numClicks + " times");
	}
}

Check the API for the interface: ActionListener.
Then search the sun tutorials for creating swing guis

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

That is done by DHTML. There are examples in the web. Just search using:
"html tabs menu"

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

The ones between the "" are strings and they will be printed they way they are. Surely you have written the Hello World program:

System.out.println([B]"Hello World"[/B]);

System.out.println([B]"Row
number "[/B] + loops + [B]" "[/B] + loops + [B]" x "[/B] + num + [B]" = "[/B] + result);

The loops, num ,results are variables. Did you try to run it and see what it prints?

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

What do you mean by "X".
Maybe this:

number " + loops + " " + loops + " [B]x[/B] " + num + " = " + result);
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Be more careful!!.
You missed the postcode. Count your arguments.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

java.util.Vector

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

v.add(1);
v.add(2);
v.add(3);

for (int i=0;i<v.size();i++) {
   int num = v.get(i);
   System.out.println(num);
}
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster
int count = 0;
while(scanner.hasNext()) {
     count++;
     System.out.println("Line "+count+" is: "scanner.next());
}

You might need a Vector because you don't know how many lines are the ones for each word.
So have a Vector for each word
When the word is found, add to the word's Vector the line number.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

That is what I mean, but why don't you run it and see what happens. If you get correct results, it means that you understood correct.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

I think you need to remove the '0' from the first number:

personalList[0] = new Personal("Paul "," White ", [B]0[/B]74078L , "51 Princes Street", "North Shields", "Tyne and Wear", 7852384379L);
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

i need to write a data validation method in which if the user enter a blank name(ex. " "), it prints an error message. if the data entered is valid (ex. "Austin"), it returns the value null.

You just said the solution:
The method will have as argument a String.
If it is empty return a message (String)
else return null (a String can be null)
Use the trim and length method to do the checking.
Check the String API for these methods

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

First of all run this code:

while(scanner.hasNext()) {
     System.out.println(scanner.next());
}

The name of the method is pretty self explanatory:
Whenever you call it it returns the next word.
In your while loop you keep calling it again and again inside the loop so every time you get the next word. This doesn't compare the same word:

if( input.next() == "a") // this will return a word
					Freq[0] = Freq[0] + 1;
				else
					if( input.next() == "if") // this will return a different word from the previous one
						Freq[1] = Freq[1] + 1;

Also use the equals method to compare objects such as the String object: if ( s.equals("a") ) { .. }

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Sum = 1+2+3+ .... + i + ...
The pattern is
Sum = Σ(i)

int sum = 0;
for (int i=0;i<N;i++) {
 sum += [B]i[/B]; // whatever is in the parenthesis Σ([B]i[/B])
}

For your sum:
1+1/1!+1/2!+1/3!...
You need to figure out what is the 'i', what is the pattern.

Compare it with the first sum

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

If you want to find a specific word from within a file, another way to do it would be to use Scanner's next() method, then use String.equals to see if they match.

Actually my solution is not correct. If a word contains the argument then it will return that it found it, even though it is not a whole word but only a part of it.

In order for my solution to work, the OP would have to use the .split(" ") method to "break" the line and then use the equals method the way you described.

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

First write a method that calculates the n!. Then use a for loop. How many times you will iterate it's up to you.
At the for loop you will use the classic algorithm for calculating sums. Declare a sum variable and add to it the result you get from inside the loop

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

JavaAddict,
sorry, to disturb you again. How can I build without having rate? e.g.

rt=d (rate multiplied by time = distance)

Thank you in advance

MJ

Your question doesn't make sense.

int distance = 80 * time;
// or
int rate = 80;
int time = ...;
int distance = rate * time;
javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

the time multiplied by 80

It's not that difficult. Multiply time by 80 and put it in the distance

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

First of all check the Scanner API. You found a code and you didn't think to check the API.

Now, there is the nextLine method that reads the next line of the file. Combine it with the has.. methods to read the entire file:

while (scanner.hasNextLine() ) {
   String line = scanner.nextLine();

// check if the line contains the words you want
int i = line.indexOf("if");
// if i==-1 then not found
}

You can store the entire file in a Vector(add each line to a vector as the loop runs) and then loop through the vector to find the words you are looking for. Or you can check the line as you read it.
You might want to use the method: String.indexOf(String s)
It will return -1 if the argument is not found (check the String API)


OR
For a more sophisticated way, use regular expressions and patterns with these methods:
http://java.sun.com/j2se/1.5.0/docs/api/java/util/Scanner.html#hasNext(java.lang.String)
or
findInLine

javaAddict 900 Nearly a Senior Poster Team Colleague Featured Poster

Please post again the code but this time, the code tags end like this:
(/CODE) not: (CODE)
Also have each class in its own code tags.
Use the (code) button when you create a post