为了训练我的 Java 技能,我为您编写了以下代码:
import java.util.*;
import java.io.*;
public class RecursiveReadNames{
public static final int MAXLINES = 10;
public static void main(String[] args) throws FileNotFoundException {
Scanner scan = new Scanner(new File("listOfNames.txt"));
String[] names = new String[MAXLINES];
readNames(names, scan, 0);
printNames(names,0);
System.out.println();
printNamesReverse(names,0);
System.out.println(totalNumberOfCharsInNames(names, 0,0));
}
static String[] readNames(String[] names, Scanner scan, int curLine) {
if(curLine >= MAXLINES)
return names;
names[curLine] = scan.nextLine();
return readNames(names, scan, curLine+1);
}
static void printNames(String[] names, int cur) {
if(cur >= names.length)
return;
System.out.println(names[cur]);
printNames(names, cur+1);
}
static void printNamesReverse(String[] names, int cur) {
if(cur >= names.length)
return;
printNamesReverse(names, cur+1);
System.out.println(names[cur]);
}
static int totalNumberOfCharsInNames(String[] names, int cur, int sum) {
if(cur >= names.length)
return sum;
return totalNumberOfCharsInNames(names, cur+1, sum+names[cur].length());
}
}