Reputation: 77
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. All looping must be performed recursively.
Jay Walker
Erol Flintstone
C. Erol Madre
Billy Pilgrim
Mickey Angels
José Francisco de San Martín
Squarebob Sponge Pants
Mischa Ternoff
Chester Peak
Al Italia
Ben Dover
Pat Pending
I am 100% lost. 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.
Finally, the part the I'm 110% lost...how the heck would I go about listing the names in reverse order? What would I use? How does recursion fit in all this?
Upvotes: 2
Views: 5911
Reputation: 82929
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 // 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"])
Upvotes: 3
Reputation: 1266
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();
}
}
}
Upvotes: 0
Reputation: 5183
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
Upvotes: 0
Reputation: 16403
To train my Java skills I wrote you the following code:
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());
}
}
Upvotes: 1
Reputation: 2102
Am not good at scanning but using Desolator's scanner you can do the rest of the part as follows,
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));
}
Upvotes: 1
Reputation:
You can read file with 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:
public static void main(String[] args) {
scanner = new Scanner(new File("myText.txt"));
readFile();
}
Upvotes: 1
Reputation: 339
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.
Upvotes: 3