简体   繁体   English

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

[英]Reading a text file in Java and printing backwards with recursion

Write a Java program that recursively reads ten names from a file, and then outputs the total number of characters in the names, the list of names, and the list of names in reverse order. 编写一个Java程序,以递归方式从文件中读取十个名称,然后以相反的顺序输出名称,名称列表和名称列表中的字符总数。 All looping must be performed recursively. 所有循环必须以递归方式执行。

Jay Walker 杰伊沃克
Erol Flintstone Erol Flintstone
C. Erol Madre C. Erol Madre
Billy Pilgrim 比利朝圣者
Mickey Angels 米奇天使
José Francisco de San Martín JoséFranciscodeSanMartín
Squarebob Sponge Pants 方形海绵裤
Mischa Ternoff 米沙特诺夫
Chester Peak 切斯特峰
Al Italia Al Italia
Ben Dover 弯腰
Pat Pending Pat Pending

I am 100% lost. 我100%迷失了。 I would like advice on where would be the first place to start. 我想建议哪里是第一个开始的地方。 Thinking about the program, I wanted to build a main that would call a scanner that would read the file first. 考虑到该程序,我想构建一个可以调用扫描程序主程序 ,它将首先读取该文件。 When reading the file, it would count the characters in the text (quick question, would a scanner count the spaces between the characters?). 在读取文件时,它会计算文本中的字符(快速问题,扫描仪会计算字符之间的空格吗?)。

Next I was thinking of just a simple print function that would display the entire names.txt file. 接下来我想到了一个简单的打印功能,它将显示整个names.txt文件。

Finally, the part the I'm 110% lost...how the heck would I go about listing the names in reverse order? 最后,我失去了110%的部分......我怎么会以相反的顺序列出名字? What would I use? 我会用什么? How does recursion fit in all this? 递归如何适合所有这些?

Pseudocode for the recursion part: 递归部分的伪代码:

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

Example output for lines ["line1", "line2", "line3"] ["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"])

Something like this: 像这样的东西:

Reader(Stream strm)
{
    string line;

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

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

Recursion will stop at the end of file and will start to unroll. 递归将在文件末尾停止并将开始展开。 The last message will be printed first. 最后一条消息将首先打印出来。

You can read file with scanner.nextLine() . 您可以使用scanner.nextLine()读取文件。 It would read an entire line includiing spaces. 它会读取整行,包括空格。

For how to print a string backwards using recursion, imagine that as a way containing houses on sides. 对于如何使用递归向后打印字符串,想象这是一种包含侧面房屋的方式。 You want to visit houses backwards (although you entered the way forwards). 你想向后看房子(虽然你已经进入了前进之路)。 So you decided to go ahead until the way's end, and then back step by step and print neighbour house names. 所以你决定继续前进,直到结束,然后一步一步地打印邻居的房子名称。

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

ADD

The code of method should be then: 方法的代码应该是:

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

Just you have to call readFile() from main: 只需要从main调用readFile()

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

Am not good at scanning but using Desolator's scanner you can do the rest of the part as follows, 我不擅长扫描,但使用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));
}

To train my Java skills I wrote you the following code: 为了训练我的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());
    }
}

do something like this 做这样的事情

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();
        }


    }

}

notice that I'm passing br object 注意我正在通过br对象

    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();
      }
 }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM