Results 1 to 4 of 4
Thread: Problem with ordering for loops
- 03-25-2009, 06:19 PM #1
Member
- Join Date
- Feb 2009
- Posts
- 8
- Rep Power
- 0
Problem with ordering for loops
For an assigment, I have to read in a text document, reverse the lines, to the last line becomes the first and etc. then i have to take the words in the line and reverse them as well. It seems like everything should work with my program, however, it refuses to make the words backwards on the last line(which is actually the first line). another example is if there is only one line of text in the document, it just prints it out, it does not take the words and reverse them.
can someone please help me debug this problem? it seems like my forloops or prints or in the wrong spot
- 03-25-2009, 06:52 PM #2
I couldn't get your link to work. Maybe you can post your code.
- 03-31-2009, 07:57 PM #3
Member
- Join Date
- Feb 2009
- Posts
- 8
- Rep Power
- 0
import java.io.*;
import java.util.*;
public class Shell
{
public static void main(String[] args)
{
Scanner console = new Scanner(System.in);
System.out.println("Enter the input file name: ");
String inputFileName = console.next();
System.out.println("Enter the output file name: ");
String outputFileName = console.next();
ArrayList<String> lines = new ArrayList<String>();
ArrayList<String> words = new ArrayList<String>();
try
{
Scanner in = new Scanner(new File(inputFileName));
PrintStream out = new PrintStream(new File(outputFileName));
while(in.hasNextLine())
{
String tempLine = in.nextLine();
lines.add(tempLine);
while(in.hasNext())
{
String token = in.next();
words.add(token);
}
}
for(int x = words.size() - 1; x >= 0; x--)
{
out.println(words.get(x));
}
for(int x = lines.size() - 1; x >= 0; x--)
{
out.println(lines.get(x));
}
in.close();
out.close();
}
catch(FileNotFoundException e)
{
System.err.println("Cannot find input file " );
System.exit(1);
}
catch(IOException e)
{
System.err.println("Cannot open input/output file " );
System.exit(2);
}
}
}
ANY IDEAS??
-
One way (semi-pseudocode):
Java Code:while scanner has next line get next line split line on whitespace "\\s+" into array of String tokens create StringBuilder for loop iterating through token array *backwards* append each token and a space " " into StringBuilder end backwards for loop add StringBuilder object.toString() into lines ArrayList at index position 0 end while loop for each line in lines arraylist println into output file end forLast edited by Fubarable; 03-31-2009 at 08:38 PM.
Similar Threads
-
[HELP]Java loops
By jude113 in forum JCreatorReplies: 0Last Post: 03-06-2009, 03:11 AM -
Question about loops
By BHCluster in forum New To JavaReplies: 4Last Post: 04-16-2008, 05:40 PM -
Loops (while do etc)
By manupr in forum New To JavaReplies: 1Last Post: 01-15-2008, 03:59 AM -
Help me: loops in java
By silvia in forum New To JavaReplies: 3Last Post: 07-19-2007, 06:47 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks