내가 이름과 또한 다른 텍스트 파일을 가질 수 있습니다 전화 번호가 텍스트 파일에서 읽기 위해 노력하고 계속하자 이 .txt :루프에서 재귀 함수의 밖으로 점프하지만 루프가
7
name1 123-456-7890
name2 098-765-4321
name3 135-792-4680
name4 246-801-3579
PHONEBOOK-FILE myBook2.txt
name5 147-025-8369
name6 150-263-7495
myBook2.txt :
1
Name7 000-222-3332
첫 줄 파일 항목의 개수는 다음 다른 파일을 의미하는 PHONEBOOK-FILE있다.
내가 배열을 사용할 수 없습니다, 내가 myBook.txt을 변경할 수 없습니다 , 나는 캐치/시도 사용할 수 없습니다, 나는
이것은 코드 내가 가진
재귀를 사용할 수 있습니다import java.util.*;
import java.io.*;
public class Phonebook
{
private boolean DEBUG = true;
private Scanner scan;
private Scanner input;
private File file;
private File holder;
private String query;
private boolean bottomOut;
private int nameCount;
private String fileNameHold;
// entry point for class
public void run()throws IOException
{
input = new Scanner(System.in);
//Gets file name and checks if it exists valid file
while(true)
{
System.out.print("Name of phone book to read in: ");
fileNameHold = input.next();
file = new File(fileNameHold);
if(file.exists())
break;
else
System.out.println("That file does not exist!");
}
System.out.println("Phonebook successfully read in!");
//Main control loop
while(true)
{
bottomOut = false;
System.out.print("Please enter person to search for: ");
query = input.next();
if(query.equals("."))
break;
file = new File(fileNameHold);
System.out.println(doWork(query, file, 0));
}
System.out.print("Thank you for using this program!");
}
//Does the searching and recursive stuff
private String doWork(String query, File fileName, int level)throws IOException
{
scan = new Scanner(fileName);
//Grabs item count fom begining of file
//if(!bottomOut)
nameCount = Integer.parseInt(scan.nextLine());
String line = "";
//Runs through entries
for(int i=0; i<nameCount; i++)
{
line = scan.nextLine();
debug("file: " +file);
debug("line: " + line);
debug("nameCount: " + nameCount);
if(line.toLowerCase().contains(query.toLowerCase()))
{
return line;
}
//Recursion is used to searth through linked files
else if(line.contains("PHONEBOOK-FILE"))
{
//System.out.println("Sanity Check");
holder = new File(line.replace("PHONEBOOK-FILE ", ""));
if(level < 2 || (level > 0 && bottomOut))
return doWork(query, holder, ++level);
else if(level >= 2 && !bottomOut)
bottomOut = true;
else
return "not found (REC)";
}
}
return "not found";
}
private void debug(String stuff)
{
if(DEBUG)
System.out.println("[[--DEBUG--]] " + stuff);
}
}
나는 가정 문제는 doWork에 있지만 잘못된 것일 수 있습니다. 그것이하고있는 일은 지정된 바닥을 치기까지 파일을 통해 재귀됩니다. 이름을 찾지 못하면 재귀를 벗어나서 PHONEBOOK-FILE 행을 계속 통과해야합니다.
현재 반환 값을 찾을 수없는 경우 해당 행을 전달한 이름을 검색하는 경우. 그것은 재귀에서 나오지 않는 것 같습니다.
당신은 아마 이것에 중대하지 않다고 말할 수 있습니다. 도움 주셔서 감사합니다.