我用反向字符串,但现在需要最终文档是原则,反之亦然:
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();
}
}
谢谢!
答案 0 :(得分: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)
将项添加到数组(先到先服务),然后反向遍历数组
for (into I = array.length; i >= 0; i--) {
//print array[i]
}
如果您不知道文档中的行数
,也可以使用ArrayList答案 2 :(得分: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
答案 3 :(得分: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();
}
}
}
感谢所有可能的解决方案