Hi mates..

I'm trying to find a way in how to inputing or outputting from a file in Java.

For my bad luck when I finished my Java course, our professor didn't talked about this thing.

I searched in the internet, and found a way in inputing from a file which is:

import java.io.File;
import java.io.FileNotFoundException;
try {
			Scanner input = new Scanner(new File("file.txt"));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

but after that, how to read the content of that file! also, if the file has a paragraph how can I search for a specific words, I think in java I can only read a line not a word!

for example "a" or "if" or "playing" how can I look for them if they exist in the file or not.

After that, how to output the data I want in an output file!


Thanks in advance.

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

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.

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.

Thanks mates for those useful links.

Sorry for that but I got confused, so which solution you think it'll be easier to implement and as you said javaAddict I want to find the WHOLE word if exist not a part of it.

like for example when I search for "ok" it wouldn't take this as a found "okay".

Thanks

http://java.sun.com/j2se/1.5.0/docs/api/java/util/Scanner.html

Using next() is the easiest way to go and will work for what you are describing. And I'm linking to the documentation because if you read the method description for next(), it will become clear what the method does. Alternatively, you could create a while loop

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

And just look at what it prints to answer your question.

commented: Good solution +4

http://java.sun.com/j2se/1.5.0/docs/api/java/util/Scanner.html

Using next() is the easiest way to go and will work for what you are describing. And I'm linking to the documentation because if you read the method description for next(), it will become clear what the method does. Alternatively, you could create a while loop

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

And just look at what it prints to answer your question.

WOW, thank you so much I'm now coding easily :D

one more thing please, if I want to check a specific word where it occurred in which line of the file, how to do that?

I mean for example "a" I want to see in which line it appears, how to do that!?


Thanks in advance.

This is my code now, WHY i'm getting an error!!

Here is the Data.java:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Data {
		
	private String[] a = {"a", "if", "is", "of", "peck", "peppers", "peter", "picked", "pickled", "piper", "that", "the", "where"};
	private int Freq[] = new int[50];
	
	public int[] getFreq() {
		return Freq;
	}
	public void setFreq(int[] f) {
		Freq = f;
	}
	
	public void searchForFreq()
	{
			Scanner input;
			try {
				input = new Scanner(new File("file.txt"));
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			while( input.hasNext() )
				{
				if( input.next() == "a")
					Freq[0] = Freq[0] + 1;
				else
					if( input.next() == "if")
						Freq[1] = Freq[1] + 1;
					else
						if( input.next() == "is")
							Freq[2] = Freq[2] + 1;
						else
							if( input.next() == "of")
								Freq[3] = Freq[3] + 1;
							else
								if( input.next() == "peck")
									Freq[4] = Freq[4] + 1;
								else
									if( input.next() == "peppers")
										Freq[5] = Freq[5] + 1;
									else
										if( input.next() == "peter")
											Freq[6] = Freq[6] + 1;
										else
											if( input.next() == "picked")
												Freq[7] = Freq[7] + 1;
											else
												if( input.next() == "pickled")
													Freq[8] = Freq[8] + 1;
												else
													if( input.next() == "piper")
														Freq[9] = Freq[9] + 1;
													else
														if( input.next() == "that")
															Freq[10] = Freq[10] + 1;
														else
															if( input.next() == "the")
																Freq[11] = Freq[11] + 1;
															else
																if( input.next() == "where")
																	Freq[12] = Freq[12] + 1;
				}
			for( int i = 0; i < Freq.length; i++ )
			{
				System.out.println( a[i] + "...." + Freq[i]);
			}
		
	}
	

}

and this is Driver.java:

public class Driver {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		Data d = new Data();
		d.searchForFreq();
		
		

	}

}

any clue on how to solve the error?

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") ) { .. }

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") ) { .. }

ahaaa omg i messed around lol

So, you mean I should first save the input in a variable and compare it
like this:

String s = input.next();
if( s.equals("a") )
blah blah
else if( s.equals("if") )
blah blah
...

That is what you meant?

And yeah I ran this code:

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

and it worked perfectly.

I did this now I used "s.equalsIgnoreCase(argu)" because some of the words in the file having CAPITAL letters.

Data.java:

/**
 * @author Q8iEnG
 *
 */
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Data {
		
	private String[] a = {"a", "if", "is", "of", "peck", "peppers", "peter", "picked", "pickled", "piper", "that", "the", "where"};
	private int Freq[] = new int[13];
	
	public int[] getFreq() {
		return Freq;
	}
	public void setFreq(int[] f) {
		Freq = f;
	}
	
	public void searchForFreq()
	{
		String s;
		Scanner input = new Scanner( System.in);
		try {
				input = new Scanner(new File("file.txt"));
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			while( input.hasNext() )
				{
				s = input.next();
				if( s.equalsIgnoreCase("a") )
					Freq[0] = Freq[0] + 1;
				else
					if( s.equalsIgnoreCase("if") )
						Freq[1] = Freq[1] + 1;
					else
						if( s.equalsIgnoreCase("is") )
							Freq[2] = Freq[2] + 1;
						else
							if( s.equalsIgnoreCase("of") )
								Freq[3] = Freq[3] + 1;
							else
								if( s.equalsIgnoreCase("peck") )
									Freq[4] = Freq[4] + 1;
								else
									if( s.equalsIgnoreCase("peppers") )
										Freq[5] = Freq[5] + 1;
									else
										if( s.equalsIgnoreCase("peter") )
											Freq[6] = Freq[6] + 1;
										else
											if( s.equalsIgnoreCase("picked") )
												Freq[7] = Freq[7] + 1;
											else
												if( s.equalsIgnoreCase("pickled") )
													Freq[8] = Freq[8] + 1;
												else
													if( s.equalsIgnoreCase("piper") )
														Freq[9] = Freq[9] + 1;
													else
														if( s.equalsIgnoreCase("that") )
															Freq[10] = Freq[10] + 1;
														else
															if( s.equalsIgnoreCase("the") )
																Freq[11] = Freq[11] + 1;
															else
																if( s.equalsIgnoreCase("where") )
																	Freq[12] = Freq[12] + 1;
				}
			for( int i = 0; i < Freq.length; i++ )
			{
				System.out.println( a[i] + "...." + Freq[i]);
			}
		
	}
	

}

here is the file content: "file.txt"

Peter Piper picked a peck of pickled peppers . A peck of pickled
peppers Peter Piper picked . If Peter Piper picked a peck of pickled peppers ,
where is the peck that Peter Piper picked ?

Now, how can I check the lines!
like each word appeared in which line? how to do this, please?

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.

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.

I ran it, and it works perfectly. and the Thanks goes to you and to BestJewSinceJC.

here is the output:

a....3
if....1
is....1
of....3
peck....4
peppers....3
peter....4
picked....4
pickled....3
piper....4
that....1
the....1
where....1

But, now I need to know how to see each word where is appeared in which line, how to do that?

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.

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.

I didn't understand the part you said about Vector, what is Vector!?

And you said Count++ for each word to be found, but if both words are in the same line! this won't work, right?

let me explain more:
1- I want to search for the word "fast" in a paragraph.
2- I found the frequency of how many times "fast" has been occurred.
3- I need to find in which lines of that paragraph the word "fast" appeared, for example "in line 1, 2, 4".

How to do that?

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);
}

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);
}

Sorry for that, but I didn't understood why I have to use Vector! I mean does the vector will recognize lines! if yes, how!

also, how should I input from the file to the Vector!

sorry, things are blurry for me :\

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.

You could also make a small class:

public class TrackWord{
String word;
int lineNumber;
int wordNumber;
}

Where word is the word itself, line number is the line the word was seen on, and word number of the word's position within that line. So for the sentence "I have a massive hangover" every word would have a line number of 1 and "massive" would have a word number of 4. You could easily implement this by doing the following:

int lineNumber = 1;
while(scanner.hasNextLine()){
String theLine = scanner.nextLine();
//theLine is now the next line from your file
Scanner lineScanner = new Scanner(theLine);
        int wordCount = 0;
        while(lineScanner.hasNext()){
                String nextWord = lineScanner.next();
        }
lineNumber++;
}

I intentionally left out some stuff from the above code (as per our homework rules), but that is the basic idea. To fully implement it, you'd have to increment wordCount in the appropriate place, and then you'd have to create a new TrackWord object, populate it with the name of the word and the line number and word number it was seen at, then add the TrackWords to an array.

P.S. Since you want to track every line where 'fast' was seen, you could modify the class I showed above so that it had an ArrayList of line numbers. Then every time you saw the word fast, you could check to see if you already have a TrackWord Object for the word fast. And if you do, then you could add the line number you just saw it at to the TrackWord's ArrayList of line numbers. I hope that made sense.

P.P.S not trying to step on your toes JavaAddict, your solution works, this seems simpler to me though. And congrats on your 1500th post :)

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

commented: actually agreed - the extra class may be more confusing than anything +4

Just wow, thank you very much for this plenty of explanation of the codes and topics.

Congratulation JavaAddict for the 1500 posts :D
Thanks a lot BestJewSinceJC, for your assist and explanation too.

Best wishes for both of you.
I'll use "javaAddict" code for the Vector, sounds awesome :D

And yeah I forgot, javaAddict nice bike you got :D congratz

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.