Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Simple Java Email Harvester Program

  1. Feb 13, 2008 #1
    Hey guys, I am learning Java and am attempting a project from a book, but I have run into a problem. I don't have an issue when it comes to harvesting an address that has whitespace on both sides. My issues come when a) the input doesn't contain whitespace on either side of an address and b) the input doesn't have an address at all (my program recognizes an address as containing an @ and whitespace on either side.

    How do I get the program to run without error considering my two issues and simply print an "@" if there is no email address present with using only the the methods I already have in my program (I cant use looping or conditional structures)?

    Here is my code thus far:

  2. jcsd
  3. Feb 13, 2008 #2


    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    Design it the right way. Use a regular expression.

    - Warren
  4. Feb 13, 2008 #3
    Ok, but if I were to stay within the bounds of using only string operations and methods, how do you suggest I fix the problem of when the input doesn't contain an email address? How would I get the program to print only an @ under this condition?
  5. Feb 13, 2008 #4
    Really, you should just use a regular expression. I'm not familiar with the Java classes for doing that but there's usually a .Success boolean property that simply tells you whether there was a match or not. If you want to reinvent the wheel, unless you give a good reason to you may not find lots of help to be forthcoming.
  6. Feb 13, 2008 #5


    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    You're using indexOf() to find an @ sign. If there is no @ sign, indexOf() will return -1. You can check to see that the result is -1, and do something about it. As it stands, your program doesn't check it, and goes on to blindly use it in the next line of code, which then throws the exception.

    - Warren
  7. Feb 13, 2008 #6
    Thanks for your help. I am going to forgo trying to find another solution (there doesn't seem to be one) and use an if-else statement to check the value like you suggested.
  8. Feb 14, 2008 #7
    Try to read this "tutorial" entirely to get a hold of how regular expressions work and how to apply them:

    In fact, right in the first page they show you an example of an email pattern
    Code (Text):
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Similar Discussions: Simple Java Email Harvester Program
  1. Simple Java Program Help (Replies: 18)

  2. Emailing Java files (Replies: 2)