2014-03-31 21 views
1

我用反向串,但现在需要的最后文件的原则是,反之亦然:反向的Java文件全文

Hello 
Bye 

Bye 
hello 

,而不是:

olleH 
eyB 

当我这样做?

这是我的源:

public static void main(String[] args) { 

    if (args.length != 1) { 
     System.err.println("Sintaxis incorrecta, introduzca el nombre del fichero"); 
     System.exit(1); 
    } 

    BufferedReader br = null; 

    try { 
     br = new BufferedReader(new FileReader(args[0])); 
     String s; 

     try { 
      while ((s = br.readLine()) != null) { 
       StringBuilder reverse = new StringBuilder(s); 
       String sCadenaInvertida = reverse.reverse().toString(); 
       System.out.println(sCadenaInvertida); 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } 
} 

谢谢!

+2

请重新表述',但现在需要的最后文件是原则,反之亦然:'。这没有意义。 –

+0

拆分为单词,反向收集,使用空间连接 –

+2

您需要接受字符串,使用'split'获取单词的数组,然后创建一个新的字符串,以降序读取单词。简单:D – AntonH

回答

1

添加项目到一个数组(先到先得),然后遍历反向

for (into I = array.length; i >= 0; i--) { 
    //print array[i] 
} 

数组或者您可以使用一个ArrayList,如果你不知道文档中的行数

1
ArrayList<String> theWords= new ArrayList<String>(); 
while ((s = br.readLine()) != null) { 
      //split line into words 
      String[] parts = s.split("\\s+"): 
      //for each word append to arraylist 
      for(String s : parts) 
      { 
       theWords.append(s); 
      } //end for loop 
} //end while loop 

// iterate array, from size-1 to 0 
int theWordsSize = theWords.size()--; 
for(int i= theWordsSize; i >= 0; i--) 
{ 
    System.out.println(theWords.get(i)); 
} //end for loop 
2

只要把一切都在一个ArrayList和使用Collections.reverse http://www.java2s.com/Code/Java/Collections-Data-Structure/ReverseorderofallelementsofJavaArrayList.htm

伪代码:

ArrayList<String> arrayList = new ArrayList<>(); 
    arrayList.add("Hello"); 
    arrayList.add("Bye"); 

    Collections.reverse(arrayList); 
    System.out.println(arrayList); 
+1

+1! – Rogue

+0

这只会通过行,而不是文字 – Dan

+0

达成一致,但它没有说任何有关倒退单词。我认为他们只是想要从输入的反向顺序。 – Scott

0

这里的答案,这是很容易:

公共类Reverse2 {

public static void main(String[] args) { 



     if(args.length != 1){ 
      System.err.println("Sintaxis incorrecta, introduzca el nombre del fichero"); 
      System.exit(1); 
     } 

     BufferedReader br = null; 


     try { 
      br = new BufferedReader(new FileReader(args[0])); 

      ArrayList<String> lista = new ArrayList<String>(); 
      String s; 

      try { 
       while((s=br.readLine()) != null){ 
        lista.add(s); 

       } 

       for(int i= lista.size()-1;i>=0;i--){ 
        System.out.println(lista.get(i)); 
       } 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 



     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } 





    } 

} 

感谢所有可能的解决方案