使用Java读取文本文件并使用递归向后打印

时间:2012-10-23 08:01:24

标签: java list loops recursion text-files

  

编写一个Java程序,以递归方式从文件中读取十个名称,然后以相反的顺序输出名称,名称列表和名称列表中的字符总数。所有循环必须以递归方式执行。

     杰克沃克   Erol Flintstone
  C. Erol Madre
  Billy Pilgrim
  米奇天使
  JoséFranciscodeSanMartín
  Squarebob海绵裤
  Mischa Ternoff
  切斯特峰   Al Italia
  本多佛   Pat Pending

我100%迷失了。我想建议哪里是第一个开始的地方。考虑到该程序,我想构建一个 main ,它将调用一个首先读取该文件的 scanner 。在阅读文件时,它会计算文本中的字符(快速问题,扫描仪会计算字符之间的空格吗?)。

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

最后,我失去了110%的部分...我怎么会以相反的顺序列出名字?我会用什么?递归如何适用于所有这些?

7 个答案:

答案 0 :(得分: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"])

答案 1 :(得分:3)

这样的事情:

Reader(Stream strm)
{
    string line;

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

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

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

答案 2 :(得分: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);
}

您只需要从main发送readFile()

public static void main(String[] args) {
     scanner = new Scanner(new File("myText.txt"));
     readFile();
}

答案 3 :(得分: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));
}

答案 4 :(得分: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());
    }
}

答案 5 :(得分: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对象

答案 6 :(得分: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();
      }
 }
}