I have browsed through questions similar to mine already on here, but have not found anything that will work for me.
Essentially what I have to do is read a file full of strings line by line, print them line by line and then word by word. I would like to accomplish this using .split to create an array of each individual string.
For instance, my file reads:
The fat cat was black
The cow jumped over the moon
I came to say hello world
etc.
I have figured out how to read the file and print the file line by line, but I cannot figure out how to print it word by word. Each of these 3 are in their own functions, so I'm not sure if that plays any role in where something is placed.
This is what I have so far in my method:
static public void printWords( String [ ] arr, int count )
{
String [] s2 = arr[0].split( " " );
for( int i = 0; i < count; i++)
{
System.out.println( s2 [i] );
}
System.out.println();
}
However, this is giving me an error. I switched around a couple things, but each time it prints either just the lines or stops at a certain point. The only thing I have in main is my method call pertaining to this, which is not the problem. If anyone has any insight it would be greatly appreciated. Thank you!
EDIT:
"Count" in my code is the number of lines in the file I am reading. So for this, it is 3.
I have tweaked the code to get what I need, however it only prints the first sentence.
String [] s2 = arr[0].split( " " );
for (int j = 0 ; j < count ; j++)
{
for( int i = 3; i < s2.length; i++)
{
System.out.print( s2 [i] + " " );
}
System.out.println();
}
}
For example, this only prints
The fat cat was black
And then ends. I am trying to construct another loop around it (as demonstrated by my code) but it ends up just printing "The fat cat was black" 3 times rather than moving to the next line of the file.
s2
, why use the count as thefor
loop condition? Why nots2.length
? – R.J Oct 17 '13 at 16:06Scanner
. (java-util-scanner) – damryfbfnetsi Oct 17 '13 at 16:06