Logic ?? Recursive Method
The recursive programming below is supposed to print
the elements in reverse order. Can someone please
explain the logic behind it. Thanks.
public void printRevList() {
if (next != null)
next.printRevList();
System.out.println(element + " " );
}
It's a little incomplete, but if it truly is a piece of functioning recursive code, then you're basically pushing everything onto a stack, first element first, last element last, and then popping it off from the most recently pushed element down to earliest pushed element.
Assume 3 elements
1) call printRevlist on first element.
2) since the next element is not null, we go on to call next.printRevList()--remember, this must complete before we can call println, and notice that since there are no braces, println is called regardless of whether or not next was null
3) We are now in the second element's printRevList, as called from the first. The first has not yet printed. Next is not null, so we call next.printRevList. We won't print element 2 until element 3's printRevList completes
4) We are now in elem 3's printRevList. This time, next is null, so we don't recurse anymore--nothing else get's pushed on the stack. We simply print "el3 " and return
5) Now we're back in elem 2's printRevList, after having just completed elem 3's printRevList. So we print "el2 " and return
6) I'll let you fill this one in.
Let me know if it's still not making sense--recursion is not the easiest thing to get your brain around.
Jeff
Similar Messages
-
Palindrome Test with Recursive Method
I was assigned in class to do make a program containing a recursive method that tests if the user's input is a palindrome. My instructor helped us out by giving us some lines of code for us to complete, however rather than helping me, they've only confused me...
package project6;
public class Palindrome {
void main(String[] args) {
// TODO code application logic here
char charArray[] = args[0].toCharArray();
public static Boolean testPalindrome(char[] text, int beg, int end) {
//First case: the fragment in question is empty
//This will be the case if beg is > end
if(beg > end)
return true;
//Second case: the fragment contains just one character
//This will be the case when beg == end.
if(beg == end)
return true;
//Third case: is it of the form "x" + s + "x"
if(testPalindrome(??, ?, ?))
else
return false;
}Firstly,
if(beg > end)
return true;How does this statement check if the array is empty? And why use >? Shouldn't it be == ?
Secondly,
if(beg == end)
return true;I understand this it to test if there is only 1 character, but don't palindromes with more than 1 character have the same beg and end? So why do this test?
Thirdly,
I don't get why a recursive function is necessary. Wouldn't it be much easier to store the input text into 2 arrays one in its original form and reversed form, and compare the two if they are identical?
I would do that, but he wants our class to follow his way ...onguy3n wrote:
I don't get why a recursive function is necessary. Wouldn't it be much easier to store the input text into 2 arrays one in its original form and reversed form, and compare the two if they are identical?
I would do that, but he wants our class to follow his way ...I guess your teacher wants to you to learn the recursive way of thinking in this exercise
I'm gonna give u the algorithm of the code your supposed to implement.
boolean isPalindrome(char[] x,int begin,int end)
//if x[begin] equals to x[end]
// return isPalindrome(x,begin+1,end-1)
// else return false
}Now every recursive function will need a terminal condition , this should go right at the beginning of the method. Your terminal condition(s) should be
//if begin>=end return trueAnd yea , ur inital call to the function should be isPalindrome(original array , 0, original array -1)
Edited by: darth_code_r on Nov 24, 2008 2:50 PM -
I need help with this recursion method
public boolean findTheExit(int row, int col) {
char[][] array = this.getArray();
boolean escaped = false;
System.out.println("row" + " " + row + " " + "col" + " " + col);
System.out.println(array[row][col]);
System.out.println("escaped" + " " + escaped);
if (possible(row, col)){
System.out.println("possible:" + " " + possible(row,col));
array[row][col] = '.';
if (checkBorder(row, col)){
System.out.println("check border:" + " " + checkBorder(row,col));
escaped = true;
else {
System.out.println();
escaped = findTheExit(row+1, col);
if (escaped == false)
escaped = findTheExit(row, col+1);
else if (escaped == false)
escaped = findTheExit(row-1, col);
else if (escaped == false)
escaped = findTheExit(row, col-1);
if (escaped == true)
array[row][col] = 'O';
return escaped;
}I am having difficulties with this recursion method. What I wanted here is that when :
if escaped = findTheExit(row+1, col); I am having trouble with the following statement:
A base case has been reached, escaped(false) is returned to RP1. The algorithm backtracks to the call where row = 2 and col = 1 and assigns false to escaped.
How do I fix this code?
I know what's wrong with my code now, even though that if
if (possible(row, col))
[/code[
returns false then it will go to if (escaped == false)
escaped = findTheExit(row, col+1);
how do I do this?Okay I think I got the problem here because I already consult with the instructor, he said that by my code now I am not updating my current array if I change one of the values in a specific row and column into '.' . How do I change this so that I can get an update array. He said to me to erase char[][] array = getArray and replace it with the array instance variable in my class. But I don't have an array instance variable in my class. Below is my full code:
public class ObstacleCourse implements ObstacleCourseInterface {
private String file = "";
public ObstacleCourse(String filename) {
file = filename;
public boolean findTheExit(int row, int col) {
boolean escaped = false;
//System.out.println("row" + " " + row + " " + "col" + " " + col);
//System.out.println(array[row][col]);
//System.out.println("escaped" + " " + escaped);
if (possible(row, col)){
//System.out.println("possible:" + " " + possible(row,col) + "\n");
array[row][col] = '.';
if (checkBorder(row, col)){
escaped = true;
else {
escaped = findTheExit(row+1, col);
if (escaped == false)
escaped = findTheExit(row, col+1);
else if (escaped == false)
escaped = findTheExit(row-1, col);
else if (escaped == false)
escaped = findTheExit(row, col-1);
if (escaped == true)
array[row][col] = 'O';
return escaped;
public char[][] getArray() {
char[][] result = null;
try {
Scanner s = new Scanner(new File(file));
int row = 0;
int col = 0;
row = s.nextInt();
col = s.nextInt();
String x = "";
result = new char[row][col];
s.nextLine();
for (int i = 0; i < result.length; i++) {
x = s.nextLine();
for (int j = 0; j < result.length; j++) {
result[i][j] = x.charAt(j);
} catch (Exception e) {
return result;
public int getStartColumn() {
char[][] result = this.getArray();
int columns = -1;
for (int i = 0; i < result.length; i++) {
for (int j = 0; j < result[i].length; j++) {
if (result[i][j] == 'S')
columns = j;
return columns;
public int getStartRow() {
char[][] result = this.getArray();
int row = -1;
for (int i = 0; i < result.length; i++) {
for (int j = 0; j < result[i].length; j++) {
if (result[i][j] == 'S')
row = i;
return row;
public boolean possible(int row, int col) {
boolean result = false;
char[][] array = this.getArray();
if (array[row][col] != '+' && array[row][col] != '.')
result = true;
return result;
public String toString() {
String result = "";
try {
Scanner s = new Scanner(new File(file));
s.nextLine();
while (s.hasNextLine())
result += s.nextLine() + "\n";
} catch (Exception e) {
return result;
public boolean checkBorder(int row, int col) {
char[][] array = this.getArray();
boolean result = false;
int checkRow = 0;
int checkColumns = 0;
try {
Scanner s = new Scanner(new File(file));
checkRow = s.nextInt();
checkColumns = s.nextInt();
} catch (Exception e) {
if ((row + 1 == checkRow || col + 1 == checkColumns) && array[row][col] != '+')
result = true;
return result;
I thought that my problem would be not to read the file using the try and catch everytime in the method. How do I do this?? Do I have to create an array instance variable in my class? -
Can we create recursive methods in ABAP objects?
Thanks in Advance !!!
Please post your questions in the correct forum.
Edited by: Rob Burbank on Oct 1, 2010 4:55 PMHi,
Yes. We can create recursive methods in ABAP Objects. You need to take care when to come out of the recursion. Otherwise it will lead to indefinite loop.
Mostly, in SAP PP module BOM related programs require recursion.
The program can be like this :
Method RECURSION.
if <condition>.
exit.
else.
call method RECURSION.
endif.
endmethod.
Please let me know if you need assistance further.
Best Regards,
Aleem Mohiuddin. -
Need help writing a recursive method
hello, im having problems with this and its already giving me a headache!!
i have to write a recursive method that receives a parameter n that prints the following:
1
12
123
1234
how would i even begin to do this...im lostErnie_9 wrote:
ok i just got a little problem. it prints
and i needed
So its only changing the order it prints it. but where would that be changed? i tried swapping the bottom part where the parameter is modified and the print but it does not workLooks like you are first decrementing the iterator and then incrementing it ....try the other way around -
"Traveling Salesman" Using recursive method
Hello,
I am attempting to make a java program that accomplishes the following.
Should read a text file cities.dat which contains a number of cities and their x, and y distances.
Example:
City1,122,123
City2,1234,123
City3, 132, 123
City4,1234,1234
The program will run for n number of cities.
The program should print every combination of cities the "salesman" can visit, keeping the first and last constant and display the final distance traveled.
Output Example:
City1, City2, City3, City 4 Final Distance = 100
City1, City3, City 2, City 4 Final Distance = 200
Here is what I have so far, I am a little stuck, mainly I beleieve in the main method. Can someone please provide instruction on how I can finish this code to work as needed?
public class Traveler {
public String city;
public int x;
public int y;
public Traveler(String next, int nextInt, int nextInt2) {
city = next;
x = nextInt;
y = nextInt2;
public static double theDistance(Traveler first, Traveler second) {
int xPoint = second.x - first.x;
int yPoint = second.y - first.y;
return Math.sqrt(xPoint * xPoint + yPoint * yPoint);
public static void recTraveler(Traveler[] travelerArr, ArrayList<Traveler> theOrder, Traveler firstOne, Traveler finalOne){
int sumofDistance = 0;
ArrayList<Traveler> travelerOrd = null;
if (travelerOrd.size() == travelerArr.length)
if(travelerOrd.get(0) == firstOne && travelerOrd.get(travelerOrd.size()-1) == finalOne)
for (int j = 0; j < travelerOrd.size() - 1; j++)
sumofDistance += theDistance(travelerOrd.get(j), travelerOrd.get(j+1));
System.out.println(sumofDistance);
for(int k = 0; k < travelerArr.length; k++)
if (travelerArr[k] != null)
Traveler temp = travelerArr[k];
travelerArr[k] = null;
travelerOrd.add(temp);
recTraveler(travelerArr, travelerOrd, firstOne, finalOne);
travelerOrd.remove(travelerOrd.size()-1);
travelerArr[k] = temp;
}//end traveler
class travelerApp {
public static void main(String[] args) throws FileNotFoundException {
ArrayList<Traveler> travelList = new ArrayList<Traveler>();
Scanner scanFile = new Scanner(new File("cities.dat"));
scanFile.useDelimiter(",");
while(scanFile.hasNext())
Traveler travel = new Traveler(scanFile.next(), scanFile.nextInt(), scanFile.nextInt());
travelList.add(travel);
} // end main()
} // end class travelerAppI have edited my code. Right now it will read and print out my text file using delimiters. However I need to utilize my recursive method in my driver program. How do I call this/utilize this? So that my output will print all the combinations of possible cities and their final distances? I need to know how to use recTravel() method is basically what I am asking.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Scanner;
public class ScanCities {
public static void main(String[] args) {
Scanner scanFile = new Scanner(System.in);
File file = new File("cities.dat");
try {
scanFile = new Scanner(new FileReader(file));
} catch (FileNotFoundException e) {
System.exit(0);
while (scanFile.hasNext()) {
parseLine(scanFile.next());
private static void parseLine(String line) {
Scanner lineScanner = new Scanner(line);
lineScanner.useDelimiter(",");
String name = lineScanner.next();
int x = lineScanner.nextInt();
int y = lineScanner.nextInt();
System.out.println(name + ", " + x + ", " + y);
import java.util.ArrayList;
public class Traveler {
public String city;
public int x;
public int y;
public Traveler(String next, int nextInt, int nextInt2) {
city = next;
x = nextInt;
y = nextInt2;
public static double theDistance(Traveler first, Traveler second) {
int xPoint = second.x - first.x;
int yPoint = second.y - first.y;
return Math.sqrt(xPoint * xPoint + yPoint * yPoint);
public static void recTraveler(Traveler[] travelerArr, ArrayList<Traveler> theOrder, Traveler firstOne, Traveler finalOne){
int sumofDistance = 0;
ArrayList<Traveler> travelerOrd = null;
if (travelerOrd.size() == travelerArr.length)
if(travelerOrd.get(0) == firstOne && travelerOrd.get(travelerOrd.size()-1) == finalOne)
for (int j = 0; j < travelerOrd.size() - 1; j++)
sumofDistance += theDistance(travelerOrd.get(j), travelerOrd.get(j+1));
System.out.println(sumofDistance);
for(int k = 0; k < travelerArr.length; k++)
if (travelerArr[k] != null)
Traveler temp = travelerArr[k];
travelerArr[k] = null;
travelerOrd.add(temp);
recTraveler(travelerArr, travelerOrd, firstOne, finalOne);
travelerOrd.remove(travelerOrd.size()-1);
travelerArr[k] = temp;
}//end travelerEdited by: Cole1988 on Mar 15, 2009 9:11 PM -
Problem with font logical names method
Concerning font logical names, the Java tutorial states: To get the logical name for a Font object, call java.awt.Font.getName. Would someone kindly offer a few lines of code to demonstrate how getName would be implemented in this regard -- say using Century Gothic as the font? I've been having trouble overcoming error messages trying to implement this.
Thanks.
Jody WidelitzPretty simple, just call getName() on a Font object once you have it. For example, this will list all the font names on your system:import java.awt.*;
public class Test
public static void main(String[] args)
Font[] fonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts();
for(int j = 0; j < fonts.length; j++)
System.out.println(fonts[j].getName());
} -
Does JBoss has allow-concurrent-calls like in Weblogic for recursive method
I have my problem listed at
http://jira.jboss.com/jira/browse/JBAS-1443
My problem is that i am using Recursive function and so I need to have my Stateful bean accessed through remote interface but such access is blocked due to EJB specification. There is one way which Jboss list is hold/queue but that cannot be a solution for Recursive function
Thanks in advance
CSJakhariaIts not about hacking. There are many instances when the facility has to be given to the user for their convenience. These type of facilities can be given with warning that it is not advisable but if it is used it is upto the user. So if the person using it can see that it will not cause any problem to the implementation can use it
Bye for now
CSJakharia -
How bad is this recursive method?
Ignore the variable names.
public static int reverse(int blah)
String temp ="";
String remaining = "";
String number = Integer.toString(blah);
if(number.length() == 1)
return (Integer.parseInt(number));
else if(number.length() != 1)
temp = number.substring(number.length()-1, number.length());
remaining = number.substring(0, number.length()-1);
temp+=reverse(Integer.parseInt(remaining));
return(Integer.parseInt(temp));
}Hello,
The code wont end if its length is >2.
Will not be recursive.
ex:
234
it will return 423
thats the only issue...
Edited by: amit.khosla on Mar 1, 2009 8:52 PM -
Tried to get help in the java programming section, but didn't find any takers... Can anyone here help?
Hello,
My error is that I'm creating a method that returns an integer, but I can't seem to fix the problem. I'm missing something. Can anyone help? My method finds the maximum value in a linked list.
public static int maxElement(Node head, int max){
current = head;
if(current == null){
System.out.println("No maximum value");
return max;
else if(current.link == null)
return max = current.info;
else if(current.info > current.link.info){
max = current.info;
return (maxElement(current.link, max));
else if(current.info < current.link.info){
max = current.link.info;
return (maxElement(current.link, max));
}With quick look this is incorrect:
else if(current.link == null)
return max = current.info;should be
else if(current.link == null)
return max;
I get the following error message: "This method must return a result of type int."
The first if statement determines if the linked list contains any nodes at all. If there are no nodes to check, the method returns max value = 0;
The second if statement determines if the linked list only contains ONE node. In that case, we return the value of that node and assign it to max. I then return max.
Here is where I think my problem is, my third and fourth if statements. I'm now comparing the first node value with the second node value...instead of returning a maximum value, I want to call the method again to compare the next two nodes...etc.
In my main method, I'm calling the method like this: System.out.print(maxElement(head,max)); head is defined as the linked list and max has been initialized to zero. -
I need some help with recursive methods.
Here's a method.
public int m1(int n)
If(n==1)
return 25;
else
return n + m1(n-1)
then you solve for:
m1(6)
alright, so I get you this up to the 25. How does the 25 get there, why wouldn't it be 1+m1(0)? and the answer for the problem is 45. Could someone explain how you get 25 and 45?
6+m1(5)
5+m1(4)
4+m1(3)
3+m1(2)
2+ m1(1)
25
m1(6)==45
thanks.How does the 25 get thereYou put it there.
the answer for the problem is 45It may be easier to see this if you write your list in the reverse order:m(1) = 25
m(2) = 2 + m(1) = 27
m(3) = 3 + m(2) = 30
m(4) = 4 + m(3) = 34
m(5) = 5 + m(4) = 39
m(6) = 6 + m(5) = 45 -
I don't understand why this recursive program is looping, or its #s.
i put in a println around the 7th line of code to see how it is working, i dont understand how to app is getting its numbers or why it is looping without a for statement. this demonstrates
recursion. the output i get is
value of n is 2
value of n is 3
Factorial of 3 is 6
value of n is 2
value of n is 3
value of n is 4
Factorial of 4 is 24
value of n is 2
value of n is 3
value of n is 4
value of n is 5
Factorial of 5 is 120
How is this possible when the only arguments passed in are 3, 4 , and 5, so that (n-1)*n would result in 6, 12, and 20. or at least thats what i thought it would produce, but instead,
it loops through 2 3 4 5 and i have no idea where its getting those numbers from. any help greatly appreciated.
public class Factorial {
// this is a recursive method
int fact(int n){
int result;
if(n==1) return 1;
result = fact(n-1) * n;
System.out.println("value of n is " + n);
return result;
class Recursion {
public static void main(String args[]) {
Factorial f = new Factorial();
System.out.println("Factorial of 3 is " + f.fact(3));
System.out.println("Factorial of 4 is " + f.fact(4));
System.out.println("Factorial of 5 is " + f.fact(5));
}Recursion is closely related to the mathematical principle of proof by induction.
You use induction to see that your recursive method is correct. Take the factorial method
of the OP:
int fact(int n){
if(n==1) {
return 1;
} else {
return n * fact(n-1);
}Some peoples' heads explode when they see a method invoking itself, as though they were
seeing a snake swallowing its tail and disappearing! Yet nothing could be simpler or more
logical. These same people have no problem when f() calls g(), so suppose the previous
code had been written:
int fact(int n){
if(n==1) {
return 1;
} else {
return n * SOMEBODY_ELSES_FACTORIAL(n-1);
}Now we are just looking at ordinary code. Suppose method SOMEBODY_ELSES_FACTORIAL
does indeed compute the factorial function. In order to implement X you need to
know something about X, right? So we need to know a few things about factorial. These are:
1! = 1
n! = n * (n-1)!, for n>1
By inspection, our code handles the n=1 case, and because we assume SOMEBODY_ELSES_FACTORIAL works,
it handles the case n>1 successfully, too.
Finally, the principle of induction tells us SOMEBODY_ELSES_FACTORIAL can in fact be the method
we are defining, fact().
QED -
Recursion with Return instruction without parameter
Please I have a doubt about following code:
public void solveTowers( int disks, int sourcePeg, int destinationPeg,
int tempPeg )
if ( disks == 1 )
System.out.printf( "\n%d --> %d", sourcePeg, destinationPeg );
return;
solveTowers( disks - 1, sourcePeg, tempPeg, destinationPeg );
System.out.printf( "\n%d --> %d", sourcePeg, destinationPeg );
If I enter witch amount variable DISK = 3
I'd like to known: Why ouput after perform the code is
1--->3
2--->3
1--->3 ?
I didn't get it about the mechanism logical of RETURN instruction !!!
Please, some could me help and explain about with mechanism
OBS: An draw or design it will be helpfull for me understant
A lot of thanks
GmouradYou didn't mention other parameters of your recursive method, so I am not guessing but here is an easier example.
public class Test{
public void resursive(int num) {
if (num == 1) {
System.out.println(num);
return;
resursive(--num);
System.out.println(num);
public static void main(String[] args) {
int num = 3;
Test myTest = new Test();
a.resursive(num);
1
1
2
recursive(3) -> recursive(2) // print 2
recursive(2) -> recursive(1) // print 1
recursive(1) -> // print 1It would print the last one first because the upper one would call itself first before print out the value. -
DELETE() method..need help!!
private void deleteAll(){
File file;
String from = "C:/A/";
try {
file = new File(from);
} catch (Exception e) {
file = null;
e.printStackTrace();
if (file != null) {
String files[] = file.list();
for(int x = 0; x < files.length ; x ++){
File f = new File (files[x]);
if(f.isFile()){
f.delete();
}else{
System.out.print("WHAT PROBLEM?");
} else {
System.out.println("no such url");
} I wish to delete all files in C:/A/ when running this method..So anyone can find out what problems with my code..Thanks
Edited by: kahleong888 on Jun 14, 2008 9:06 PMKah,
To "prune" a whole directory and it's contents you need to depth-first-recurse the tree, (logically) pruning the branch you are standing on the way back up the tree... and if you (logically) recurse a "directory tree" from the "root" at the top... down to the "leaves" at the bottom, then shouldn't "trees" be called "roots" instead of "trees"... Hmmm... Just one of those things.
It goes something like this:
package forums;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
class Pruner
public static void main(String[] args) {
String top = args.length>0 ? args[0] : "C:/tmp/test/directoryToPrune";
try {
long start = System.currentTimeMillis();
int n = prune(top);
long took = System.currentTimeMillis()-start;
System.out.println("Removed "+n+" objects from "+top+" in "+took+" milliseconds.");
} catch (Exception e) {
e.printStackTrace();
private static int prune(String dirName)
throws FileNotFoundException, IOException
File dir = new File(dirName);
if ( !dir.exists() ) {
throw new FileNotFoundException("Not found: "+dir.getCanonicalPath());
return recursivePrune(dir);
private static int recursivePrune(File dir)
throws FileNotFoundException, IOException
String fullname = dir.getCanonicalPath();
int count = 0;
if ( dir.isDirectory() ) {
for (File file : dir.listFiles()) {
count += recursivePrune(file);
// having removed dir's contents we continue and remove dir.
// if dir isn't a dir then it must be a SINGLE file, soft-link, named-pipe...
if (!dir.delete()) {
throw new IOException("Failed to delete file: "+fullname);
return count+1;
}I recommend you move the prune(String dirName) method (and it's recursivePrune(...) helper method) to an abstract utilz class (something like $yourInitials.utilz.io.Dirz), and make it public of course.
Cheers. Keith. -
hi guys, I have almost done everything, except one thing that gives me a grief all the time.. perhaps it's kinda stupid, but.. can someone please take a pick at this code (I know its huge) and help me with how to call those static methods. everytime I'm receiving messages like "cannot resolve symbols" but I cannot figure out what is it wrong and how am I suppose to invoke them:((
thanks!
any kind of help is appreciated:)
// the program works its way through webpages and locates email addresses, collects them and prints them out
// limitations:
// - maximum of 100 web pages
// - maximum of 100 email addresses
// - maximum of 100 lines per web page
import java.io.*;
import java.net.*;
import java.util.*;
// This class uses an array to keep track of email addresses
class emailClass {
private int EMailArrayMax = 100;
private int EMailArrayCounter = 0;
private String[] EMailArray = new String [EMailArrayMax];
// AddElement method
// adds an address to the array
// if the array is not full
// - convert the address to lower case
// - add the address to the array
public void addElement(String Address, String Element)
if (EMailArrayCounter < EMailArrayMax)
EMailArray[EMailArrayCounter] = Element;
String sAddress = Address.toLowerCase();
// printAll method
// prints the entire array of email addresses
public static void printAll(String[] EMailArray, int EMailArrayMax)
for (int a=0; a<EMailArrayMax; a++)
System.out.println(a + " " + EMailArray[a]);
// contains method
// checks to see if an email address is already in the array
// see if the address is in the array
// return true if it is
// return false if it is not
public boolean contains(String Data)
boolean found = false;
for (int a=0; a<EMailArrayCounter; a++)
if (EMailArray[EMailArrayCounter].compareTo(Data)==0)
found = true;
return found;
// Links class
// it keeps track of what pages have been visited
// it is IDENTICAL to the email class
class LinksClass
private int LinksArrayMax = 100;
private int LinksArrayCounter = 0;
private String[] LinksArray = new String [LinksArrayMax];
public static void printAll(String[] LinksArray, int LinksArrayMax)
for (int a=0; a<LinksArrayMax; a++)
System.out.println(a + " " + LinksArray[a]);
public boolean contains(String Data)
boolean found = false;
for (int a=0; a<LinksArrayCounter; a++)
if (LinksArray[LinksArrayCounter].compareTo(Data)==0)
found = true;
return found;
// the main class
public class SpamMaster {
static boolean debug = true;
// the main recursive method that retrieves the webpages
public static void GetPage(String PageAddress, // the name of the webpage to retrieve
int Depth, // the depth
emailClass EMail, // the emailclass object that should add found email addresses to
LinksClass Links) { // the linksclass object that should add found links to
// print the address of the page that we are working on
System.out.println("http://www.google.ca/search?q=find+me&ie=UTF-8&oe=UTF-8&hl=en&btnG=Google+Searc
h");
// check to see if we have gone to deep
// Do nothing if the depth is < 0;
if (Depth < 0)
// hold the entire web page in single string.
// that will make it easy to tear apart using the StringTokenizer
String contents = "";
// now ... open the webpage, add it to the String one line at a time
// add a space between the lines as you add them together
try {
URL url = new URL(PageAddress);
BufferedReader inStream = new BufferedReader(
new InputStreamReader(url.openStream()));
String line = inStream.readLine();
while (line != null)
// add the line to the array
contents = contents + " " + line;
line = inStream.readLine();
catch (Exception e)
System.out.println("Sorry, page not found");
// check for email addresses
// print the address to the screen too so we can see what is going on
StringTokenizer stEmail = new StringTokenizer(contents); //break on whitespace
String sEmail;
while (stEmail.hasMoreTokens())
sEmail = stEmail.nextToken().toLowerCase();
// check for the "@" ... that means we have an email address
// look for the "@" in the token in sEmail
if (sEmail.indexOf("@") >= 0) {
// print the email address to the screen
System.out.println(sEmail);
// check to see if the email address is in the email object already
// if it is not, add it.
// okey dokey. Let's see if there are any links on the page
// assuming that a link is of the form <a href = "http://.......">
// use a StringTokenizer
StringTokenizer st = new StringTokenizer(contents, "\n \t\">"); //break on newline, blank, tab, ", and
greater-than
String s;
while (st.hasMoreTokens()) {
s = st.nextToken().toLowerCase();
// check for the "<a" ... that means we have a link!
if (s.equals("<a")) { // check for the <a
s = st.nextToken().toLowerCase();
if (s.indexOf("href") == 0) { // then it must start with the word href
s = st.nextToken();
if (s.toLowerCase().indexOf("http://") == 0) { //an absolute link URL
// at this point, we have found a link!
// it is in the variable s
// check to see if the link is in the links object
// if it is ... do nothing
// if it is not in the links object ... do the following
// - add the link to the object
// - print a message that a link is being added ... print the link so you know what it is
// - call this method that we are in now ... GetPage (yes, that is recursion).
// calling the method, do the following:
// - pass the method call the link that you just found
// - pass it maximumdepth reduced by one
// - pass the email and links objects so they can be used
// the main method
public static void main(String[] args) throws IOException
BufferedReader kb = new BufferedReader (new InputStreamReader (System.in));
// create a email address object
emailClass email = new emailClass();
// create a links object
LinksClass Links = new LinksClass();
// create a String variable for the start web page address
String StartPage;
// create an int variable for the maximum depth
int Depth = 5;
// ask the user for the start web page address
System.out.println("Enter the start web page:");
// use http://www.google.ca/search?q=find+me&ie=UTF-8&oe=UTF-8&hl=en&btnG=Google+Search to test
things with
StartPage = kb.readLine();
// ask the user for the maximum depth
System.out.println("Enter the depth:");
String Depth1 = kb.readLine();
// call the GetPage method that traverses the website
// pass it:
// - web page address to visit
// - maximum page depth
// - email object
// - visitedpages object
GetPage(PageAddress, Depth, emailClass, LinksClass);----------------> what else to put if not this?
// print the results
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("Results");
System.out.println("*******");
System.out.println("");
System.out.println("Pages Visited:");
// call the printAll method of the links object
printAll( I KNOW ITS STUPID BUT I DONT KNOW WHAT TO PUT ANYMORE:((( !!! );
System.out.println("");
System.out.println("Email Addresses Found:");
// call the method to print the email addresses
printAll( );
// got to call the method to save the email addresses to file herein line:218 you have:
GetPage(PageAddress, Depth, emailClass, LinksClass);
This will result in a "cannot resolve symbol error" because
1) PageAddress is not defined in your main method nor is it defined in your main class. You have to declare and initialize it to something: eg: String PageAddress = "whatever you want";
2) emailClass is a class. You want to pass the instance of that class that you created. In line 185 you did emailClass email = new emailClass(); so you want to pass the object email.
3) same thing for LinksClass. Don't pass the class, pass the object that you created. Line 189:
LinksClass Links = new LinksClass();
=)
Liam
Maybe you are looking for
-
Airport Extreme dropping out and can't connect PC anymore
Hello Suddenly, a couple of weeks ago, my internet connection dropped in the middle of surfing. I couldn't reconnect, Airport was only seeing the base station spasmodically and when I did try to connect I was being asked for a password which wasn't r
-
I've trying to relocate and download my subscription to a new computer and just keep getting an error 1 message ( some other download going on-which is not the case) anyone else have this problem
-
Acrobat fails to open after software update (end of March 2012) in Lion
When opening a PDF in Acrobat x Pro the programme crashes, ever since I did a software update at the end of March 2012. I have also been having problems with emailing PDFs, with emails disappearing or getting corrupted. Seems worse if I have Firefox
-
While typing keyboard starts typing wrong letters
I have checked my settings for my keyboard and have changed keyboards. I can open Pagemaker 7 & start typing, all's well. Then after a while it starts typing wrong letters & I can't use my short cuts. I also tryed reloading Pagemaker 7. I have run Ma
-
After my iMAC's software was updated, my USB flash drive is no longer working. What can I do? Disk Utility, Nope. So, what is the best data recovery software out there for USB drives?