Reputation: 23
I am currently stuck on what to do with my code. I must open a file and then inside of a while loop I have to get each line one at a time then I must reverse it then print it. This is what I have so far:
public class ReverseFileContents
{
public static void main(String[] args) throws FileNotFoundException
{
Scanner myScanner = new Scanner(System.in);
Scanner diskScanner = new Scanner (new File("reverse"));
while (inputFile.hasNextLine())
{
}
}
}
This is all I have after this point I am lost and just don't know which direction to go with the arraylist and using BufferedReader. Could anybody help me further this along?
Upvotes: 0
Views: 90
Reputation: 5440
This will do i believe..!!
File file = new File(filename);
Scanner in = new Scanner(file);
while (in.hasNextLine()){
System.out.println(reverse(in.nextLine()));
}
public String reverse(String text){
String reverse="";
for( int i = text.length - 1 ; i >= 0 ; i-- )
reverse = reverse + text.charAt(i);;
return reverse;
}
Upvotes: 1
Reputation: 3283
This sounds like a homework assignment, and so I'm going to avoid giving you the algorithm you need.
Here are some tips about getting a file and going through it line by line:
File filename = new File("file.txt");
Scanner file = new Scanner(filename);
ArrayList<String> lines = new ArrayList<String>();
while(file.hasNextLine()){
String line = file.nextLine();
//You can manipulate the line in here and do whatever you want
//This can also store the data into an ArrayList for later if you need
myReverse(line);
lines.add(line);
}
Here is a starting point for a reverse method. There are dozens of ways to accomplish this task:
public void myReverse(){
//convert the string into an array
//move through the array backwards printing the values
}
Upvotes: 0