I need to use Scanner and StringTokenizer to find a word then print that line in text area when found it.
This is the Search Button's coding :

private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {                                          
        try {
            Scanner scan = new Scanner(file);
            String search = txtSearch.getText();
            while (scan.hasNextLine()) {
                line = scan.nextLine();
                StringTokenizer st = new StringTokenizer(line, ":");
                while (st.hasMoreTokens()) {
                    word = st.nextToken();
                    if (word == search) {
                        txtOutput.setText("DVD List\n" + line);
                    } else {
                        txtOutput.setText("DVD Not Found");
                    }
                }
            }
            scan.close();
            SearchWin.dispose();
        } catch (IOException iox) {
        }
    }

inside the text file is something like this:
Bleach:Anime:1999:G
Avatar:Sci-Fi:2009:PG-13
Toy Story:Animation:1995:G
The Proposal:Comedy:2009:PG-13

In this text file, i am using the ":" as my seperator.

but when I input a title at the textfield then press the search button, it will only show DVD Not Found. Can someone tell me where is the problem here?

There are a couple of problems. The first problem is where you are trying to compare two Strings (non-primative) using the == operator. That is reserved for comparing primatives (char, int ...). A string has a built in operator for comparison. So to fix the intial problem change the line:

word == search

to

word.equals(search)

The second problem comes in where you do not exit your loop. So if you supplied a word that exists in a line above the last then the next time the loop goes through (or on the last line), the value in the textbox will just be overwitten.

You will need to break out of your loop if you found your word.
For example:

...
word = st.nextToken();
if ([B]word.equals(search)[/B]) {
    txtOutput.setText("DVD List\n" + line);
    [B]break;[/B]
} else {
    txtOutput.setText("DVD Not Found");
}
...

Cheers

Hmm....it still cannot search the DVD title inside my text file and got this "DVD Not Found" output in my text area when i click the search button....

Please post the code as it stands

Here is the code

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Scanner;
import java.util.StringTokenizer;
public class DVDList extends javax.swing.JFrame {

    String line, Mline, word, DVDlist = "D:/My Documents/NetBeansProjects/DVD-List/DVD_Collection.txt";
    DVD dvd;
    LinkedList<DVD> list = new LinkedList<DVD>();
    File file = new File(DVDlist);

    /** Creates new form DVDList */
    public DVDList() {
        initComponents();
        readFile();
    }

//this button open a new internal frame to let user input dvd info
private void btnaddActionPerformed(java.awt.event.ActionEvent evt) {                                       

        AddWin.getAccessibleContext();
        AddWin.setVisible(true);
        AddWin.setSize(300, 280);

    }  

//after input info click this ok button it will save it into list
private void btnOkActionPerformed(java.awt.event.ActionEvent evt) {                                      

        String title = txtTitle.getText();
        String category = txtCategory.getText();
        String year = txtYear.getText();
        String rate = txtRate.getText();

        dvd = new DVD(title, category, year, rate);
        list.add(dvd);

        txtTitle.setText("");
        txtCategory.setText("");
        txtYear.setText("");
        txtRate.setText("");
        AddWin.dispose();

    }     

//this button will save everything in list into the text file
private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {                                        
        try {
            FileWriter fw = new FileWriter(file);
            PrintWriter pw = new PrintWriter(fw);

            Iterator it = list.iterator();
            while (it.hasNext()) {
                DVD dvd = (DVD) it.next();
                pw.println(dvd.getTitle() + ":" + dvd.getCategory() + ":" + dvd.getYear() + ":" + dvd.getRate());
            }
            fw.close();

        } catch (IOException iox) {
        }

//this button will open an internal frame let user input 
//dvd title they want to search in the text file
private void btnsearchActionPerformed(java.awt.event.ActionEvent evt) {                                          
        SearchWin.getAccessibleContext();
        SearchWin.setVisible(true);
        SearchWin.setSize(360, 160);
    }

//after the user input the dvd title, click this search button 
//to start searching and print it in text area when found
private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {                                          
        try {
            Scanner scan = new Scanner(file);
            String search = txtSearch.getText();
            while (scan.hasNextLine()) {
                line = scan.nextLine();
                StringTokenizer st = new StringTokenizer(line, ":");
                while (st.hasMoreTokens()) {
                    word = st.nextToken();
                    if (word.equals(search)) {
                        txtOutput.setText("DVD List\n" + line);
                        break;
                    } else {
                        txtOutput.setText("DVD Not Found");
                    }
                }
            }
            scan.close();
            SearchWin.dispose();
        } catch (IOException iox) {
    }

public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new DVDList().setVisible(true);
            }
        });
    }

    private void readFile() {
        try {
            Scanner scan = new Scanner(file);
            scan.useDelimiter(":");

            while (scan.hasNextLine() == true) {
                line = scan.nextLine();
                StringTokenizer st = new StringTokenizer(line);
                while (st.hasMoreTokens()){ 
                    String title = st.nextToken(":");
                    String category = st.nextToken(":");
                    String year = st.nextToken(":");
                    String rate = st.nextToken(":");
                    dvd = new DVD(title, category, year, rate);

                    list.add(dvd);
            }
            }
        } catch (IOException e) {
        }
    }


public class DVD {

    public String title, category, year, rate;

    public DVD(String t, String c, String y, String r) {
        title = t;
        category = c;
        year = y;
        rate = r;
    }

    public String getTitle() {
        return title;
    }

    public String getCategory() {
        return category;
    }

    public String getYear() {
        return year;
    }

    public String getRate() {
        return rate;
    }
    }
}

wondering why it cannot read the token in my text file and print that line...

Sorry the problem you are having is you are not breaking out of the outer loop. I should have made that more clear.

To fix this apply a label such as "outer loop" to the while statement that loops through the lines. Then in your break statement break out of that loop.

...
outer_loop:
while (scan.hasNextLine()) {
	line = scan.nextLine();
	StringTokenizer st = new StringTokenizer(line, ":");
	while (st.hasMoreTokens()) {
		word = st.nextToken();
		if (word.equals(search)) {
			txtOutput.setText("DVD List\n" + line);
			break outer_loop;
		} else {
			txtOutput.setText("DVD Not Found");
		}
	}
}
...

Yes Finally it's work ^.^
Thx a lot cale.macdonald

just now found out what if i wan search the text file by category or rating?
it will only show 1 DVD info only by using coding above

is that anyway to make it show multiple DVD info that match the search text?

For example user input and search the DVD rating "PG-13". And the output will list out all rate "PG-13" DVD in the text area.

just now found out what if i wan search the text file by category or rating?
it will only show 1 DVD info only by using coding above

is that anyway to make it show multiple DVD info that match the search text?

For example user input and search the DVD rating "PG-13". And the output will list out all rate "PG-13" DVD in the text area.

For this you will need to remove that break statement, to allow your loop to keep going.

Also before the outer loop you will need to initialize a variable (prob a string).

Each time that a record is found add that line to the string (separate it by whatever you want). If the record is not found just ignore that line.

After looping though your file, take the string variable and put its contents into the text area.

Cheers

Sorry I'm quite new to the java and cannot catch what you mean....

private void btnShow4ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        try {
            Scanner scan = new Scanner(file);
            String search = txtSRate.getText();
            String getline;
            while (scan.hasNextLine()) {
                line = scan.nextLine();
                StringTokenizer st = new StringTokenizer(line, ":");
                while (st.hasMoreTokens()) {
                    word = st.nextToken();
                    if (word.equals(search)) {
                        getline = scan.nextLine();
                        txtOutput.setText("DVD List\n" + getline + "\n");
                    } else {
                        txtOutput.setText("");
                    }

                }
            }
            scan.close();
            RateWin.dispose();
        } catch (IOException iox) {
        }
    }

it will got the java.util.NoSuchElementException: No line found
what the problem is it.....

You are getting the NoSuchElementException in your IF statement. This occurs because you are trying to get the next line (from the file) and it doesnt exist. I changed up your code slightly. Instead of using a String to hold the values of the lines i made a string builder. this will allow it to hold a greater number of lines (if your file gets bigger). I also removed the else statement (see comments).

Read through the changes and if you have any questions please ask.

private void btnShow4ActionPerformed(java.awt.event.ActionEvent evt) {                                         
	try {
		Scanner scan = new Scanner(file);
		String search = txtSRate.getText();
		StringBuilder builder = new StringBuilder();//use this to store the lines found
		while (scan.hasNextLine()) {
			line = scan.nextLine();
			StringTokenizer st = new StringTokenizer(line, ":");
			while (st.hasMoreTokens()) {
				word = st.nextToken();
				if (word.equals(search)) {
					builder.append(line).append("\n");
					
					//removing this as you will do it later 
					//txtOutput.setText("DVD List\n" + getline + "\n");
				}
				/*
				Ignore the else as it doesnt
				really matter if line wasn't found here
				else {
					txtOutput.setText("");
				}*/

			}
		}
		
		//so at this point we have all the lines found
		//so its time to update the text field
		String found = builder.toString();
		if(found.length() > 0)
		{
			//update the text field here with the values
		}
		else
		{
			//we don't have any records found
		}
		
		scan.close();
		RateWin.dispose();
	} catch (IOException iox) {
	}
}

ok i got it already thx a lot

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.