2

编写一个Java程序,递归地从一个文件中读取十个名字,然后依次输出名字中的字符总数、名字列表、名字列表。所有循环都必须递归执行。

Jay Walker
Erol Flintstone
C. Erol Madre
Billy Pilgrim
Mickey Angels
José Francisco de San Martín Squarebob
海绵裤
Mischa Ternoff
Chester Peak
Al Italia
Ben Dover
Pat Pending

我100%迷路了。我想建议从哪里开始。考虑到这个程序,我想构建一个主程序,它会调用一个首先读取文件的扫描仪。读取文件时,它会计算文本中的字符(快速提问,扫描仪会计算字符之间的空格吗?)。

接下来我想到了一个简单的打印函数,它可以显示整个names.txt文件。

最后,我迷失了 110% 的部分......我怎么会以相反的顺序列出名字?我会用什么?递归如何适应这一切?

4

7 回答 7

3

递归部分的伪代码:

function printLines(lines):
    if lines not empty:
        print first line from lines // this prints lines in order
        call printLines(remaining lines)
        print first line again      // this prints lines in reverse order

行的示例输出["line1", "line2", "line3"]

line1   // 1st output for printLines(["line1", "line2", "line3"])
line2   // 1st output for printLines(["line2", "line3"])
line3   // 1st output for printLines(["line3"])
        //  no output for printLines([])
line3   // 2nd output for printLines(["line3"])
line2   // 2nd output for printLines(["line2", "line3"])
line1   // 2nd output for printines(["line1", "line2", "line3"])
于 2012-10-23T08:10:25.267 回答
3

像这样的东西:

Reader(Stream strm)
{
    string line;

    if(!strm.eof())
    {
        line = strm.ReadLine();
        Reader(strm);
    }

    // Info - char counte etc
    string parseResult = Parse(line);
    Print(parseResult);
}

递归将在文件末尾停止并开始展开。最后一条消息将首先打印。

于 2012-10-23T08:13:09.407 回答
1

您可以使用scanner.nextLine(). 它将读取包括空格在内的整行。

对于如何使用递归向后打印字符串,想象一下它是一种在侧面包含房屋的方式。您想向后参观房屋(尽管您进入了前进的方向)。所以你决定继续前进,直到路的尽头,然后一步一步地返回并打印邻居的房子名称。

function print( i )
     if i == wayEnd
        return
     print(i + 1) // go ahead
     // after you return, print:
     output house at i

添加

方法的代码应该是:

private static Scanner scanner;
private static void readFile() {
      if (!scanner.hasNext()) return;
      String line = scanner.nextLine();
      readFile();
      System.out.println(line);
}

只需readFile()要从 main 调用:

public static void main(String[] args) {
     scanner = new Scanner(new File("myText.txt"));
     readFile();
}
于 2012-10-23T08:10:00.937 回答
1

为了训练我的 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());
    }
}
于 2012-10-23T08:32:24.873 回答
1

我不擅长扫描,但使用 Desolator 的扫描仪,您可以按如下方式完成其余部分,

private Scanner scanner;
static Map<String, Integer> counts = new HashMap<String, Integer>(); 
public static void main(String[] args) {
 scanner = new Scanner(new File("myText.txt"));
 readFile();
 System.out.println(counts);
}
 private void readFile() {
          if (!scanner.hasNext()) return;
          String line = scanner.nextLine();
          String[] names = line.split("([\\W\\s]+)");
          for(int i=0;i<names.length;i++) {
              populateMap(names[i]);
          }
          readFile();
    }
static void populateMap(String str) {
    counts.put(reverse(str), str.length());     

}
static String reverse(String s) {
    if(s.length() == 0)
        return "";
    return s.charAt(s.length() - 1) + reverse(s.substring(0,s.length()-1));
}
于 2012-10-23T08:16:57.753 回答
0

做这样的事情

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;


public class Test {
    public static void printname(String name,BufferedReader br)
    {

        if(name!=null && br!=null)
        {
            try {
                Test.printname(br.readLine(), br);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println(name);
        }
    }
    static Scanner scanner1 = new Scanner(System.in);

    public static void main(String[] args)
    {
        //print the names and total character in each name
        try {
            FileInputStream fin=new FileInputStream("d:\\file.txt");
            BufferedReader br=new BufferedReader(new InputStreamReader(fin));
            String n;
            while((n=br.readLine())!=null)
            {
                System.out.println(n+" length:"+n.length());
            }
            fin.close();
            br.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        //print names in reverse order
        try {
            FileInputStream f=new FileInputStream("d:\\file.txt");
            BufferedReader br=new BufferedReader(new InputStreamReader(f));
            try {
                Test.printname(br.readLine(),br);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            f.close();
            br.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    }

}

注意我正在传递 br 对象

于 2012-10-23T08:30:00.040 回答
0
    import java.util.Scanner;
    import java.io.*;
  class Listnames{
   public static void recursiveRead(Scanner scanner) {
      String name; 
      if(scanner.hasNext())   
       {name=scanner.next();
        recursiveRead(scanner);
       System.out.println(name.length() +" "+ name);  
       }
   }

  public static void main(String[] args)
 {
 try{
    Scanner scanner=new Scanner(new File("name.txt"));
    scanner.useDelimiter(System.getProperty("line.separator"));

   recursiveRead(scanner); 
   }
catch (FileNotFoundException e) {
      e.printStackTrace();
      }
 }
}
于 2012-10-23T09:06:22.580 回答