import java.io.*;
import java.util.Scanner;
class FileReverse{
public static void main(String[] args) throws IOException{
//charAt(int index): Returns the char value at the specified index.
//substring(int beginindex, int endindex): Returns a new string that is a substring of the string.
//valueOf(char c): Returns the string representation of the char argument
Scanner in = null;
PrintWriter out = null;
String line = null;
String[] token = null;
int i ,n ;
// check number of command line arguments is at least 2
if(args.length < 2){
System.out.println("Usage: FileCopy <input file> <output file>");
System.exit(1);
}
// open files
in = new Scanner(new File(args[0]));
out = new PrintWriter(new FileWriter(args[1]));
// read lines from in, extract and print tokens from each line
while( in.hasNextLine() ){
// trim leading and trailing spaces, then add one trailing space so
// split works on blank lines
line = in.nextLine().trim() + " ";
// split line around white space
token = line.split("\\s+");
// reverses the input and prints it to the console.
n = token.length;
for(i=0; i<n; i++){
stringReverse(token[i],(n-1));
System.out.println(token);
}
}
// close files
in.close();
out.close();
}
public static String stringReverse(String s, int n){
if(n == 0){
return s.charAt(0) + "";
}
char let = s.charAt(n);
return let + stringReverse(s,(n-1));
}
}
我们得到一个包含此输入的文件
abc 定义 你好
jkl mnop q
rstu v wxyz
并且它必须返回为
中国篮球协会
GFED
嗯
lkj
庞姆
q
乌兹别克斯坦
v
我的代码可以编译,但我不断收到indexoutofboundsException,但我无法解决这个问题。非常感谢您的帮助!
最佳答案
您将在每个空格处拆分字符串
。在下面的代码中
n = token.length;
for(i=0; i<n; i++){
stringReverse(token[i],(n-1));
System.out.println(token);
}
您检查有多少个元素由空格分隔。但您犯的错误是,您将 n-1
解析为函数 Stringreverse
(除了您不存储返回值的事实之外)。您正在使用第二个参数作为 String
的 length
,但您当前正在做的是,
您传递的是用空格分割初始 String
后返回的数组元素的数量。您应该将其称为:
for(i=0; i<n; i++){
String reversed = stringReverse(token[i],token[i].length()-1);
System.out.println(reversed);
}
关于java - 如何反转数组中的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36589552/