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));
}
}
We are given a file with this input
abc defg hi
jkl mnop q
rstu v wxyz
and it must be returned as
cba
gfed
ih
lkj
ponm
q
utsr
v
zyxw
My code compiles but I keep getting an indexoutofboundsexception and I can't figure out to fix this. Help would be greatly appreciated!
gingfedcome from?stringReverse(token[i],(n-1));is pointless anyway. You need to do something with the returned value.