I'm trying to reverse words and lines from a file, but my code only reverses the words without keeping the formatting of each sentence and printing a new line.

This is an example of the file and how the output should look.

reverse.txt (Actual) :

He looked for a book.
He picked up the book.
He read the book.
He liked the book.

Expected result:

book. the liked He
book. the read He
book. the up picked He
book. a for looked He

Here is the JAVA code I have so far

import java.io.*;
import java.util.*;

public class ReverseOrder {

  public static void main (String[] args)
        throws FileNotFoundException {

    ArrayList<String> revFile = new ArrayList<String>();

    Scanner input = new Scanner(new File("reverse.txt"));
        while (input.hasNext()){
            revFile.add(input.next());
    for(int i = revFile.size()-1; i >= 0; i--){
        System.out.println(revFile.get(i) + " ");   
    }
    }
}
}
有帮助吗?

解决方案

You can try this :-

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

public class ReverseOrder {

    /**
     * @param args
     */
    public static void main(String[] args) throws FileNotFoundException {
        // TODO Auto-generated method stub
        ArrayList<String> revFile = new ArrayList<String>();

        Scanner input = new Scanner(new File("/reverse.txt"));
            while (input.hasNextLine()){
                revFile.add(input.nextLine()); 
            }
            for(int i = (revFile.size()-1); i >=0 ; i--){
                String ar[]=revFile.get(i).split(" ");

                for(int j = (ar.length-1); j >=0; j--){
                    System.out.print(ar[j] + " "); 
                }
                System.out.println(" ");
                ar=null;
            }


        }
}

Output :-

  book. the liked He  
  book. the read He  
  book. the up picked He  
  book. a for looked He

Hope it will help you.

其他提示

my Yoda-like suggestion

    public static void main(String[] args) {
        String s = "I want cake today.";
        String[] ss = s.split(" ");
        Stack<String> sss = new Stack<>(); 
        for(String ssss:ss){
            sss.push(ssss);
        }

        while(!sss.isEmpty()){
            System.out.print(sss.pop());
            System.out.print(" ");
        }
    }

gives

today. cake want I 

for lines, do the same with another Stack.

Or, if you don't want to use Stacks, store tokens and lines into some ArrayList and use Collections.reverse(list)

You can use

  org.apache.commons.lang.StringUtils;

It has wide range of method related to String. For your purpose you could use: StringUtils.reverseDelimited(str, ' ') function like follows :

 while (input.hasNext()) {
        String str = input.nextLine();
        System.out.println(str);
        System.out.println(StringUtils.reverseDelimited(str, ' '));// <- reverse line 
    }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top