Hi, I need help getting the basic idea of how to begin writing this Strings program:

file has last name(1word) & email address
objective of prgm is to validate email address

  • 1 "@" symbol; no space left of it
  • 1 "."; no space on both sides of it

output 2 files

  1. last name & valid email
  2. last name & invalid email & reason why invalid

object-oriented programming required!

will I have more than 1 object? do i validate everything together in one method? how many methods should i end up with? is this more based on comparing content of two or more objects OR similar to the concept of anagrams? what is the key to understanding & writing this program well? how would you rate the difficulty level of this program?


I'm sure once I get the general idea of how to lay out this program, it won't be so bad (hopefully). So could someone please point me into the right direction. FYI i'm taking intro to java, so this should be very basic and simple, but it's just i'm not so advanced in the language yet to come up with the solution promptly! So some help would be greatly appreciated!!! Thank you!

so far I have been able to put this much information together:

class: PERSON

attributes: lastName, emailAdd

methods: readFile, writeOutcome, validateFile

um are there going to be arrays?

arrays: validEmail, invalidEmail, validLastName, invalidLastName

Numbers of methods is irrelevant and it would vary from developer to developer. What they will have in common is:
- have way to read file
- store retrieved values
- evaluation of retrieved data
- writing data in files

So take it from here and think what you can do from here and which of above 4 steps can be decomposed further down

so far I have been able to put this much information together:

class: PERSON

attributes: lastName, emailAdd

methods: readFile, writeOutcome, validateFile

um are there going to be arrays?

arrays: validEmail, invalidEmail, validLastName, invalidLastName

NO this looks like bad structured application.

You want to have object person that has attribute last name and email, with methods to set and get values of these parameters. It is your program that will have methods to read & write plus validation. As for arrays, you better to use collections like ArrayList, List, Vector etc that can dynamically change size unlike array that has pre-terminated size

validation rules are invalid, solution rejected.

Yeah, but the validation rules for email addresses are quite complicated and I doubt the OP has made up the rules posted above, they are created by his teacher.

in fact it's impossible to "validate an email address" using just a check of its content.
Not only does it inevitably yield a lot of false positives, it will also yield false negatives as noone ever takes into account all possible protocols and variants.

in fact it's impossible to "validate an email address" using just a check of its content.
Not only does it inevitably yield a lot of false positives, it will also yield false negatives as noone ever takes into account all possible protocols and variants.

What you say is correct in industry, above is just school assignment that is set to test student knowledge for working with strings.

and which shows the complete disconnect between what punters are taught in school and the real world...

Yes, but unfortunately there is really little we can do about it...
Few options open

  • write a book
  • take teaching position
  • try to establish connection between industry Java developers and academic to understand each other

However this went off topic.

Is there anything else student.09 you want to discuss?

um ok now i'm a little confused on how this validation portion of the program is going to work out. like how will i validate the email addresses to make sure it contains those specific symbols since just 'check' won't do the trick. Strings seem so difficult!

prior to recieving any program in this we are given a program with the similar basic idea to help us but, i'm not able to relate this program to the two prior to this one. One was checking two anagrams (two different words with the same letters ex: silent & listen). And the other program made the usage of objects. Now, i'm not sure for this one which example to follow; do either of those programs seem to have the same basic concept that could possible help me in this program. I can post a portion of each of those programs on here if that may help see where i'm coming from. This program had seemed short and simple when i first read it, but now it looks to be more complicated than i thought.

Okay, I see why you suggested to have an object: person, but i'm confused on the atttibutes & methods that I listed, were they also not right?

NO this looks like bad structured application.

You want to have object person that has attribute last name and email, with methods to set and get values of these parameters. It is your program that will have methods to read & write plus validation. As for arrays, you better to use collections like ArrayList, List, Vector etc that can dynamically change size unlike array that has pre-terminated size

Okay, I see why you suggested to have an object: person, but i'm confused on the atttibutes & methods that I listed, were they also not right?

You will use these methods, but they had no direct relevance to person object.

Why don't you try to put in coding changes that I suggested on Person object (Person object will have no main method only parameters, constructor and some setter and getter methods). Then write a class, let call it TestPerson, that has main method, provides read and write method, validation method and makes use of Person object. In case of TestPerson skeleton of methods will do just fine, at the moment I'm interested only in Person class.

//This program reads the email id in a text file and validates it. Try using this. It may help you. Incase of any issue please revert back.

import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class FileRead 
{
   public static void main(String args[])
  {
     String emailId = "";
	   try{
    // Open the file that is the first 
    // command line parameter
    FileInputStream fstream = new FileInputStream("Full path of the file goes here");
    // Get the object of DataInputStream
    DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String strLine;
    //Read File Line By Line
    while ((strLine = br.readLine()) != null)   {
      // Print the content on the console
      System.out.println (strLine);
      emailId = strLine;
      
    }
    boolean valid = validateEmailId(emailId);
    //Close the input stream
    in.close();
    }catch (Exception e){//Catch exception if any
      System.err.println("Error: " + e.getMessage());
    }
  }
   
   public static boolean validateEmailId(String emailId)
   {
	 //Input the string for validation
	      
	   boolean valid = false;
	      //Set the email pattern string
	      Pattern p = Pattern.compile(".+@.+\\.[a-z]+");

	      //Match the given string with the pattern
	      Matcher m = p.matcher(emailId);

	      //check whether match is found 
	      boolean matchFound = m.matches();

	      if (matchFound){
	        System.out.println("Valid Email Id.");
	      	valid = true;
   			}
	      else{
	        System.out.println("Invalid Email Id.");
	        valid = false;
	      }

	   return valid;
   }
}

Hi, I need help getting the basic idea of how to begin writing this Strings program:

file has last name(1word) & email address
objective of prgm is to validate email address

  • 1 "@" symbol; no space left of it
  • 1 "."; no space on both sides of it

output 2 files

  1. last name & valid email
  2. last name & invalid email & reason why invalid

object-oriented programming required!

will I have more than 1 object? do i validate everything together in one method? how many methods should i end up with? is this more based on comparing content of two or more objects OR similar to the concept of anagrams? what is the key to understanding & writing this program well? how would you rate the difficulty level of this program?


I'm sure once I get the general idea of how to lay out this program, it won't be so bad (hopefully). So could someone please point me into the right direction. FYI i'm taking intro to java, so this should be very basic and simple, but it's just i'm not so advanced in the language yet to come up with the solution promptly! So some help would be greatly appreciated!!! Thank you!

Edited 6 Years Ago by peter_budo: Keep It Organized - For easy readability, always wrap programming code within posts in [code] (code blocks)

Don't worry I won't go against that rule of the forum. I will definetely show my full effort. You may check my other thread, in which I have worked with full dedication to complete a program, which i'm finishing right now. I appreciate all your guys help, and wont let you down. I will put my full devotion to this program after my java final that is tomorrow. I guess I posted for help too soon, but please dont get me wrong I will work with you because I completely understand the your purpose to take time out and help me and I respect that. Thank you.

Comments
this kid deserves the help

Ok, sorry I haven't been active on this thread, it's just I was trying to clear things up of what I need to do with this problem. After looking at what Madhusudhan_Ram posted; I realized that seems to be a higher level of programming than what we learned in class. so i went ahead and tried to break this problem down into pieces and do it step by step. Obviously I haven't finished but I got a rough idea/layout of what I'm trying to write this program like if you get what I mean. I followed an example that we went over in class; and this is how far I have gotten but I'm very confused on the syntax and if what i'm doing is right. so if someone could please overlook my work so far and guide me step by step (little by little) from this point. Here's the rough draft of the program so far:

import java.util.Scanner;
public class EmailCheck
{
	public static void main(String[] args) throws Exception
	{
		java.io.File filein = new java.io.File("emails.txt");
		java.io.File fileout1 = new java.io File("validEmails.txt");
		java.io.File fileout2 = new java.io.File("invalidEmails.txt");
		Scanner input = new Scanner(filein);
		java.io.PrintWriter output1 = new java.io.PrintWriter(fileout1);
		java.io.PrintWriter output2 = new java.io.PrintWriter(fileout2);

		String[] email = new String[];
		String[] lastName = new String[];
		String reason;
		writeHeadings(output1, output2);
		while (input.hasNext())
		{
			fileRead(input,email);
			checkEmail(email);
			WriteOutput(output1, output2, validEmail, invalidEmail, reason)
		}
		input.close();
		output1.close();
		output2.close();
	}

	public static void fileRead(Scanner input, String[] email, String[] lastName)
	{
		
	}
	
	public static void boolean checkEmail(String[]email)
	{
		String s;
		boolean isValid;
		char @;

	}
	
	public static void writeOutput(java.io.PrintWriter output1, java.io.PrintWriter output2, String[]validEmail, String[] invalidEmail, String reason)
	{
		if (validEmail)
			output1.printf(    )
		else
			output2.printf(    )
		
		
	}
	
	public static void writeHeading(java.io.PrintWriter output1, java.io.PrintWriter output2)
	{
		output1.printf("%20s%20s", "ValidsLastName", "ValidEmail");
		output2.printf("%20s%20s%15s", "InvalidsLastName", "InvalidEmail", "Reason");
		
	}
	
}

fyi this is due Monday :(

Edited 6 Years Ago by student.09: n/a

Hi;
Syntaxe error:

java.io.File fileout1 = new java.io File("validEmails.txt");

put instead:

java.io.File fileout1 = new java.io[B].[/B]File("validEmails.txt");

You should not do that:

String[] email = new String[];

You have to define the size like:

String[] email = new String[12]; //for instance

syntaxe error:

writeHeading[B]s[/B](output1, output2);

you mean

writeHeading(output1, output2);

and some more
please clean up the code.
Hope it helps

public static void boolean checkEmail(String[]email)

A function could never be void an boolean in the same time.

char @;

You mean maybe

char a;

semicolon missed

output1.printf(    );
//AND
output2.printf(    );
//And
WriteOutput(output1, output2, validEmail, invalidEmail, reason);

Chek the declaration of the fileRead method and it's call

Wrang call

checkEmail(email);

Edited 3 Years Ago by Dani: Formatting fixed

okay, i went ahead and made those changes to my program! But I'm confused about the last one "checkEmail," what do you mean by that?

and also about the '@' symbol that's the symbol that i'm asked to look for in the program so i thought thats how i declare it.

okay, i went ahead and made those changes to my program! But I'm confused about the last one "checkEmail," what do you mean by that?

This is related to that error

public [B]static void boolean[/B] checkEmail(String[]email)
	{
		.......
	}

so ovoding it will resolve the first.

and also about the '@' symbol that's the symbol that i'm asked to look for in the program so i thought thats how i declare it.

@ is not permited in naming identifier.
It is some sort of "reserved char".
Hope it helps.

I was referringn to this part, what do you mean by this:

Chek the declaration of the fileRead method and it's call

Wrang call

checkEmail(email);

Just correct this

public static void boolean checkEmail(String[]email)
	{
		......
	}

This is not considered as a static as long as it is wrong;
so makin the call upon it in the main function (tha is a static context) will causes an error at compile time like this:
non-static method checkEmail(....) can not be referenced from static method.
So just correct above code and it will be ok.

oh ok, yes I went ahead and corrected that, now over all is my program headed in the right direction?

what should be my nxt focus? Is the main atleast correct or should I work on the invidual method/functions first?

In fact you should forget about the code abouve. and folow the peter_budo's suggection.
Create first the class Student or Peroson with only the getters and the setters is the fist step.

Ok, sorry but i'm confused because that's not how we covered it in class. I mean here is the example that we went over in class prior to him handing ou tthis program, so i'm assuming this program that i'm currently working on should look something like this

import java.util.Scanner;
public class CheckAnagram
{
	public static void main(String[]) throws Exception
	{
		java.io.File filein = new java.io.File("worddata.txt");
		java.io.File fileout = new java.io.File("wordinfo.txt");
		Scanner input = new Scanner(filein);
		String{} words = new String[2];
		boolean anagram;
		writeHeading(output);
		while(input.hasNext())
		{
			readWords(input, words);
			anagram = testWords(words);
			writeResults(output, words, anagram);
		}
		input.close();
		output.close();
	}


	public static void readWords(Scanner input, String[] words)
	{
		words[0] = input.next();
		words[1] = input.next();
	}

	public static boolean testWords(String[] words)
	{
		String s;
		boolean isAnagram;
		char ch;
		int i, x;
		
		if(words[0].length() == words[1].length())
		{
			s = words[1];
			isAnagram = true;
			i = 0;
			while (isAnagram && i< words[0].length())
			{
				ch = words[0].charAt(i);
				x = s.indexof(ch);
				if (x == -1)
					isAnagram = false;
				else
				{
					s = s.substring(0,x) + s.substring(x+1);
					i++;
				}
			}
		}
		else
			isAnagram = false;
		return isAnagram;
	}

	public static void writeResults(java.io.PrintWriter output, String[] words, boolean anagram)
	{
		if(anagram)
			output.printf("%13s%-20s%-14s%6s", " ", words[0], word[1], "Yes");
		else
			output.printf("%13s%-20s%-14s%5s", " ", words[0], words[1], "No");
		output.println();
	}

	public static void writeHeading(java.io.PrinterWriter output)
	{
		output.printf("%20s%20s%15s", "String1", "String2", "Anagram?");
		output.println();
		output.println();
	}
}

oh, i'm so sorry, I was in a hurry that I had a few typos, but I fixed those, so please try it now:

import java.util.Scanner;
public class CheckAnagram
{
	public static void main(String[] args) throws Exception
	{
		java.io.File filein = new java.io.File("worddata.txt");
		java.io.File fileout = new java.io.File("wordinfo.txt");
		Scanner input = new Scanner(filein);
		java.io.PrintWriter output = new java.io.PrintWriter(fileout);
		String[] words = new String[2];
		boolean anagram;
		writeHeading(output);
		while(input.hasNext())
		{
			readWords(input, words);
			anagram = testWords(words);
			writeResults(output, words, anagram);
		}
		input.close();
		output.close();
	}


	public static void readWords(Scanner input, String[] words)
	{
		words[0] = input.next();
		words[1] = input.next();
	}

	public static boolean testWords(String[] words)
	{
		String s;
		boolean isAnagram;
		char ch;
		int i, x;

		if(words[0].length() == words[1].length())
		{
			s = words[1];
			isAnagram = true;
			i = 0;
			while (isAnagram && i< words[0].length())
			{
				ch = words[0].charAt(i);
				x = s.indexOf(ch);
				if (x == -1)
					isAnagram = false;
				else
				{
					s = s.substring(0,x) + s.substring(x+1);
					i++;
				}
			}
		}
		else
			isAnagram = false;
		return isAnagram;
	}

	public static void writeResults(java.io.PrintWriter output, String[] words, boolean anagram)
	{
		if(anagram)
			output.printf("%13s%-20s%-14s%6s", " ", words[0], words[1], "Yes");
		else
			output.printf("%13s%-20s%-14s%5s", " ", words[0], words[1], "No");
		output.println();
	}

	public static void writeHeading(java.io.PrintWriter output)
	{
		output.printf("%20s%20s%15s", "String1", "String2", "Anagram?");
		output.println();
		output.println();
	}
}

I guess may be I'm asking for too much or i'm confusing everyone with this program, since everyon comes with a different level of programming and since this is a very basic college course assignment i'm sure there may be many different ways to write it better; but for the course we are to only use the topics we covered, if you see where i'm coming from. So, I was wondering maybe it will be easier if it was possible to come up with the pseudocode for this program and then I can go ahead and write the java program that way atleast we will have the logic part cleared up and I could follow that has my guide to write the java. Also this way, I will have more java program down to get checked, right? So would someone please be able to help me come up a simple pseudocode for this program? I had worked on it, but again not sure if its right so far:

[B][U]MAIN[/U][/B]
START
s <-- 0
writeHeading (module)
DO WHILE NOT EOF
	fileRead (module)
	checkEmail (module)
		email (s) <-- s +1
	writeOutput (module)
ENDDO
STOP
[B][U]fileRead[/U][/B]
Read email, lastName
[B][U]writeHeading[/U][/B]
*heading details here*
[B][U]writeOutput[/U][/B]
IF emailValid = true THEN
	Write email into validEmails, lastName into validEmails
ELSE
	Write email into InvalidEmails, lastName into InvalidEmails
ENDIF
[B][U]checkEmail[/U][/B]

again sorry for being difficult, i really dont mean to be, but i guess as an intro to java student: get confused and lost very easily :(

Hi again
if "Object-oriented programming techniques are to be used." as it is requared the it's Ok; you can just do some few changes to the code abouve and you can do some think like:

public class CheckMail {

    public static void main(String[] args) throws Exception {
        boolean isValide;
        //mail file
        java.io.File filein = new java.io.File("mails.txt");
        //valide mail filr
        java.io.File fileout = new java.io.File("valide.txt");
        //unvalide mail file
        java.io.File ufileout = new java.io.File("unValide.txt");
        Scanner input = new Scanner(filein);
        //File writers
        java.io.PrintWriter output = new java.io.PrintWriter(fileout);
        java.io.PrintWriter uoutput = new java.io.PrintWriter(ufileout);
        /**
         * Data
         * record[0] holds the name
         * record[1] holds the mail
         * record [2] holds the cause
         */
        String[] record = new String[3];

        writeHeading(output);
        writeHeading(uoutput);
        while (input.hasNext()) {
            readMails(input, record);
            isValide = ckeckMails(record);
            if(isValide){
            writeResults(output, record, isValide);
            }else{
                writeResults(uoutput, record, isValide);
            }
        }
        input.close();
        output.close();
        uoutput.close();
    }

    public static void readMails(Scanner input, String[] record) {
        record[0] = input.next();
        record[1] = input.next();
    }

    public static boolean ckeckMails(String[] record) {
        String mail = record[1];
        mail=mail.trim();
        String[] splitdot = mail.split("\\.");
        String[] splitAt = mail.split("@");
        boolean isValidAt = false;
        boolean isValidDot = false;
        String cause = "";

        if (((splitAt.length == 2) && (splitAt[0].charAt(splitAt[0].length() - 1) != ' '))) {
            isValidAt = true;
        } else {
            cause = "symbol \"@\" must occur exactly once nad There must be a non-blank character to the left of the \"@\" symbol";
            isValidAt = false;
        }
        if (splitdot.length > 1) {
            isValidDot = true;
            for (int i = 0; i < splitdot.length - 1; ++i) {
                if ((splitdot[i].charAt(splitdot[i].length() - 1) == ' ') || (splitdot[i + 1].charAt(0) == ' ')) {
                    isValidDot = false;
                    cause += " Every occurrence of the character \" . \" must have a non-blank character on either side.";
                    break;
                }

            }
        } else {
            //invalide cause:
            cause += " There must be atleast 1 \" . \" in the email address.";

        }

        if (!(isValidDot && isValidAt)) {
            record[2] = cause;
        }
        return isValidDot && isValidAt;
    }

    public static void writeResults(java.io.PrintWriter output, String[] validatedRecord, boolean isValid) {
        if (isValid) {
            output.printf("%20s%20s%15s%20s", " ", validatedRecord[0], validatedRecord[1], "Yes ");
        } else {
            output.printf("%20s%20s%15s%20s",  validatedRecord[0], validatedRecord[1], "No ",validatedRecord[2]);
        }
        output.println();
    }

    public static void writeHeading(java.io.PrintWriter output) {
        output.printf("%20s%20s%15s%20s", "name", "mail", "is valid","cause");
        output.println();
        output.println();
    }

}

Hope it helps.

This question has already been answered. Start a new discussion instead.